Sub topic 3
Parameters and return values
This chapter assumes you can build and run a program with cargo, know Rust's primitive types, and understand let and let mut. It covers how a function receives values and how it hands one back.
Typed parameters
Every parameter needs a type annotation. The compiler does not infer parameter types, so the signature is a complete contract between caller and function.
fn add(a: i32, b: i32) -> i32 {
a + b
}
fn main() {
let sum = add(2, 3);
println!("{sum}");
}Parameters of the same type still need one annotation each. Writing a, b: i32 is a compile error.
Arguments are passed by value. For simple types such as i32, the value is copied. For types that own heap data, such as String or Vec<i32>, the value is moved, and the caller can no longer use it. The chapter on passing references shows how to borrow instead.
The return type
The return type follows ->. If you leave it out, the function returns (), the unit type, which carries no information.
The body of a function is a block. The value of the block's final expression becomes the return value, as long as that expression has no trailing semicolon.
fn double(x: i32) -> i32 {
x * 2
}Adding a semicolon turns the expression into a statement. The block then evaluates to (), which no longer matches i32:
fn double(x: i32) -> i32 {
x * 2;
}The compiler reports a mismatched types error and points at the semicolon. This is one of the most common mistakes for newcomers to Rust.
Returning more than one value
A function has one return type, but that type can be a tuple.
fn min_max(values: &[i32]) -> (i32, i32) {
let mut min = values[0];
let mut max = values[0];
for &v in values {
if v < min {
min = v;
}
if v > max {
max = v;
}
}
(min, max)
}
fn main() {
let (lo, hi) = min_max(&[4, 9, 2, 7]);
println!("{lo} {hi}");
}The caller destructures the tuple directly in a let. This function panics on an empty slice, because values[0] is out of range. A more careful version would return Option<(i32, i32)>.
How a call flows
Early return with `return`
The return keyword exits the function immediately with a value. Use it for early exits, and use the final expression for the normal result.
fn safe_div(a: i32, b: i32) -> Option<i32> {
if b == 0 {
return None;
}
Some(a / b)
}
fn main() {
println!("{:?}", safe_div(10, 2));
println!("{:?}", safe_div(1, 0));
}Idiomatic Rust avoids a return on the last line. Write Some(a / b), not return Some(a / b);.
Parameter details
| Feature | Behavior |
|---|---|
| Type annotation | Required on every parameter |
| Default values | Not supported |
| Named arguments | Not supported, arguments are positional |
| Overloading | Not supported, one function per name in a scope |
| `mut` on a parameter | Allowed, makes the local binding mutable |
A mut parameter changes only the function's own copy or moved value. It does not affect the caller's variable.
fn countdown(mut n: u32) -> u32 {
while n > 3 {
n -= 1;
}
n
}
fn main() {
let start = 10;
println!("{}", countdown(start));
println!("{start}");
}This prints 3, then 10. The variable start is a separate copy, so it keeps its value.
Exercise
What does this function return, and does it compile? fn square(x: i32) -> i32 { x * x; }
Show answer
It does not compile. The semicolon after x * x makes it a statement, so the block evaluates to () instead of i32. Removing the semicolon fixes it, and the function then returns the square of x.
Exercise
Write a function swap(a: i32, b: i32) that returns the two values in reverse order, and show how a caller binds both results.
Show answer
fn swap(a: i32, b: i32) -> (i32, i32) { (b, a) } and the call let (x, y) = swap(1, 2); gives x = 2 and y = 1.