


Defining Functions with Parameters in Rust
In Rust, defining a function that accepts parameters is straightforward. When you declare a function, include parameters within parentheses right after the function name, ensuring you specify both the parameter name and its data type. For example:Defining parameters with explicit types not only enhances code readability but also leverages Rust’s strong type system to prevent many common programming errors.
Example: Greeting with a Parameter
The following example demonstrates a simple function that accepts a person’s name as a parameter and prints a personalized greeting. In themain function, the greet function is called with different arguments to generate greetings dynamically.
greet function takes a &str parameter called name and uses it within the println! macro to display a custom greeting. When you run the program, you will see the following output:
Example: Calculating the Area of a Rectangle
Functions can handle multiple parameters. The example below uses thecalculate_area function to compute the area of a rectangle using its width and height.
calculate_area function multiplies two i32 parameters and returns the resulting product. The result is then stored in the area variable and printed.
Example: Adding a Prefix to a Message
Another common scenario is formatting a message by adding a prefix. Theadd_prefix function combines a prefix with a message to create a formatted string. See the example below:
add_prefix function uses two &str parameters along with the format! macro to produce dynamic, formatted output based on the provided inputs.
Summary
Parameters are a critical concept in programming that enable functions to be modular, dynamic, and reusable. In Rust, you define functions with parameters by using thefn keyword, which is followed by the function name, a list of parameters with their types, and the function’s code block. Real-world examples, such as generating personalized greetings, calculating areas, and adding prefixes to messages, illustrate how parameters empower developers to write clean, maintainable, and efficient code.
