return function rust
To define a function that returns a value in Rust, you can use the fn
keyword followed by the function name, input parameters, and return type. Here's an example:
fn add_numbers(a: i32, b: i32) -> i32 {
let sum = a + b;
sum
}
In this example, the add_numbers
function takes two i32
integers as input parameters and returns their sum as an i32
. The sum
variable holds the result of the addition, and it is implicitly returned at the end of the function.
You can call this function and assign the returned value to a variable like this:
let result = add_numbers(3, 5);
The result
variable will hold the value 8
, which is the sum of 3
and 5
.