Concept Flow - Return values
Start function
Execute statements
Evaluate return expression
Return value to caller
Function ends
This flow shows how a Rust function runs its code and then sends a value back to where it was called.
fn add(a: i32, b: i32) -> i32 {
a + b
}
fn main() {
let result = add(2, 3);
println!("{}", result);
}| Step | Action | Expression Evaluated | Return Value | Output |
|---|---|---|---|---|
| 1 | Call add(2, 3) | N/A | N/A | N/A |
| 2 | Evaluate a + b | 2 + 3 | 5 | N/A |
| 3 | Return 5 to caller | 5 | 5 | N/A |
| 4 | Assign return value to result | result = 5 | 5 | N/A |
| 5 | Print result | println!("{}", 5) | 5 | 5 |
| Variable | Start | After Step 2 | After Step 4 | Final |
|---|---|---|---|---|
| a | N/A | 2 | N/A | N/A |
| b | N/A | 3 | N/A | N/A |
| result | N/A | N/A | 5 | 5 |
Rust functions return the value of their last expression without needing 'return'.
Add a semicolon to make it a statement, which returns '()' instead.
Use '-> Type' to specify return type.
Returned value goes back to the caller and can be stored or used.
Example: fn add(a: i32, b: i32) -> i32 { a + b }i32 value?-> Type to specify return type after function parentheses.-> i32 correctly; others use invalid syntax or wrong type name.fn multiply(x: i32, y: i32) -> i32 {
x * y
}
fn main() {
println!("{}", multiply(4, 5));
}i32:fn get_number() -> i32 {
let x = 10;
return;
}i32 but uses return; without value.fn check_value(x: i32) -> bool {
if x > 0 {
true
} else {
false
}
}
fn main() {
println!("{}", check_value(-3));
}Pass the test and this pattern moves unknown