Function Parameters and Return Values in Rust
Function Parameters and Return Values
3
Functions are an essential part of any programming language, and Rust is no different. In Rust, functions have parameters and return values.
Here's what you need to know about them:
- Function Parameters:
In Rust, function parameters are defined inside the parentheses after the function name. You can specify as many parameters as you need, separated by commas.
Here's an example of a function that takes two parameters:
fn add_numbers(num1: i32, num2: i32) -> i32 { num1 + num2 }
In this example, the function add_numbers
takes two parameters, num1
and num2
, and returns their sum. The data type of the parameters is specified after the parameter name, in this case, i32
which is a 32-bit signed integer data type.
- Function Return Values:
In Rust, a function can return a value by using the return
keyword followed by the value you want to return. Alternatively, you can return a value without specifying the return
keyword. In the example above, there is no return
statement, but the function is still returning a value because of the last line in the function, which is an expression that evaluates to num1 + num2
.
Here's an example of a function that explicitly returns a value using the return
keyword:
fn get_greeting(name: &str) -> String { return format!("Hello, {}!", name); }
In this example, the function get_greeting
takes a single parameter, name
, which is a reference to a string (&str
). It returns a new String
object that contains a greeting message with the name parameter.
In Rust, the last statement of a function is what the function returns, so you can often simplify the function by omitting the return
keyword and instead using an expression as the last statement.
March 27, 2023