Sub topic 3
Parameters and Return Values
This chapter covers how Rust functions receive data and hand results back. It assumes you can build and run a program with cargo, know the primitive types (integers, booleans, strings), and understand let and let mut. You should also know the difference between a statement and an expression from the previous chapter. The final-expression rule below depends on it.
Declaring parameters
Every parameter needs an explicit type. Rust does not infer parameter types from the body or from call sites. The compiler checks each function on its own, so the signature is a complete contract.
fn add(a: i32, b: i32) -> i32 {
a + b
}
fn main() {
let sum = add(2, 3);
println!("{sum}");
}Each parameter is written name: Type, separated by commas. A trailing comma is allowed. The return type follows ->. The call add(2, 3) is an expression of type i32, so you can bind it, pass it on, or use it inside a larger expression.
Parameters have several properties worth knowing:
- Arguments are matched by position. Rust has no named arguments and no default values.
- Rust has no function overloading. Two functions in the same scope cannot share a name, even with different parameter lists.
- Each parameter is a local variable that is immutable by default. Writing
mut a: i32makes the local binding mutable. That change affects only the function's own copy or owned value, not the caller's variable. - Argument types must match exactly. Passing an
i64where ani32is expected is a compile error. Convert explicitly, for example withi32::try_from(x)orx as i32.
The final expression is the return value
A function body is a block. The value of a block is the value of its last expression, provided that expression has no trailing semicolon. In add, a + b is the returned value.
Adding a semicolon turns the expression into a statement. The block then evaluates to (), the unit type, and the compiler reports a mismatch with the declared i32.
fn add_broken(a: i32, b: i32) -> i32 {
a + b;
}
fn main() {
println!("{}", add_broken(1, 2));
}This program does not compile. The error says the function has return type i32 but its body evaluates to (), and it usually points at the semicolon. This is one of the most common mistakes for people arriving from C-like languages.
A function with no -> clause returns (). These two declarations are equivalent:
fn log_line(msg: &str) {
println!("{msg}");
}
fn log_line_explicit(msg: &str) -> () {
println!("{msg}");
}
fn main() {
log_line("one");
log_line_explicit("two");
}Idiomatic code omits -> ().
Early return with `return`
You can leave a function before its last expression by using return. It is useful for guard checks at the top of a function.
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));
}Use return for early exits and a bare final expression for the normal result. Writing return x; as the last line works but is considered noisy, and Clippy flags it as needless_return.
Returning multiple values with tuples
A function returns exactly one value. To produce several, return a tuple and destructure it at the call site.
fn min_max(values: &[i32]) -> Option<(i32, i32)> {
let first = *values.first()?;
let mut lo = first;
let mut hi = first;
for &v in &values[1..] {
if v < lo {
lo = v;
}
if v > hi {
hi = v;
}
}
Some((lo, hi))
}
fn main() {
if let Some((lo, hi)) = min_max(&[4, -2, 9, 0]) {
println!("{lo}..{hi}");
}
}Tuples are fine for two or three closely related values. Beyond that, a named struct is easier to read because the fields carry names.
How values move in and out
Passing an argument to a function transfers it the same way a let binding would. The rules depend on the type:
| Argument type | What happens on a call | Caller can still use it? |
|---|---|---|
| `Copy` type such as `i32`, `bool`, `char` | The value is copied | Yes |
| Owned non-`Copy` type such as `String` or `Vec<i32>` | Ownership moves into the function | No, unless the function returns it |
| Shared reference `&T` | A borrow is created | Yes |
| Mutable reference `&mut T` | An exclusive borrow is created | Yes, after the call ends |
The return value follows the same rules in the other direction. Returning an owned value moves it to the caller, which then owns it.
fn shout(s: String) -> String {
let mut out = s;
out.push('!');
out
}
fn main() {
let greeting = String::from("hello");
let loud = shout(greeting);
println!("{loud}");
// println!("{greeting}"); // error: borrow of moved value
}After shout(greeting), the variable greeting is no longer valid because ownership moved into the function. The function hands a String back, and the caller binds it as loud. Moving a String copies only its pointer, length, and capacity, not the text on the heap, so returning large values is cheap.
When the function only needs to read or edit the data, borrow it instead. Borrowing is covered in detail in a later chapter, but the signature difference matters here:
fn length_of(s: &str) -> usize {
s.len()
}
fn append_bang(s: &mut String) {
s.push('!');
}
fn main() {
let mut text = String::from("hi");
println!("{}", length_of(&text));
append_bang(&mut text);
println!("{text}");
}Here the caller keeps text throughout.
Choosing parameter types
Prefer the most general borrowed type that does the job:
- Take
&strrather than&String. A&Stringcoerces to&strautomatically, so callers can pass either a string literal or a borrowedString. - Take
&[T]rather than&Vec<T>. Callers can then pass arrays, slices, and vectors. - Take
Tby value when the function needs to own the data, for example to store it in a struct or return it.
Choosing owned or borrowed is a design decision, not a performance trick. The signature tells readers whether the function consumes, reads, or modifies its input.
Return types and what the compiler checks
All paths through a function must produce a value of the declared return type. The compiler checks every return and the final expression against it.
fn sign(n: i32) -> i32 {
if n < 0 {
return -1;
}
if n > 0 {
return 1;
}
0
}
fn main() {
println!("{} {} {}", sign(-5), sign(0), sign(8));
}Because if is an expression, the same function can also be written with the branches as the result. Both forms are valid, and the choice is about readability. A chain of guard checks reads well with return. A choice between values reads well as one if/else expression.
Missing a branch produces a type error. If an if without an else is the last expression in a function that returns i32, the compiler complains, because an if without else has type ().
The return type cannot be left out of the signature and inferred. A function that returns a value must always say so after ->. The one flexible form is impl Trait, which names a trait the returned type implements without spelling the concrete type, and it appears later in the tutorial series.
Parameter patterns
A parameter is a pattern, not just a name. You can destructure tuples and references directly in the signature.
fn distance_from_origin((x, y): (f64, f64)) -> f64 {
(x * x + y * y).sqrt()
}
fn sum_pair(&(a, b): &(i32, i32)) -> i32 {
a + b
}
fn main() {
println!("{}", distance_from_origin((3.0, 4.0)));
println!("{}", sum_pair(&(2, 5)));
}This is occasionally handy, but only use it when it makes the body shorter and clearer. Most code uses plain names.
Common errors
- Trailing semicolon on the result. The function returns
()instead of the declared type. Remove the semicolon from the last expression. - Mismatched integer types.
add(a_i64, 3)fails when the parameter isi32. Convert at the call site. - Use after move. Passing a
StringorVecby value and then using it again fails. Pass a reference, clone it, or use the returned value. - Forgetting
&mutat the call site. Callingappend_bang(text)when it expects&mut Stringis an error. Rust requires you to write&mut text, which makes mutation visible to the reader. - Mutating a non-
mutbinding.&mut textrequireslet mut text. Declaring the variable withoutmutmakes the borrow fail. - Missing return path. An
ifwithoutelse, or a branch that falls off the end, leaves a type of()where a value is required.
Data flow in a call
The diagram shows what happens when the caller passes arguments and receives a result.
Exercises
Exercise
This function fails to compile with "expected i32, found ()". Why, and what is the one-character fix?
fn square(n: i32) -> i32 {
n * n;
}
Show answer
The trailing semicolon makes n * n; a statement, so the block evaluates to () instead of an i32. Removing the semicolon makes n * n the final expression, which is returned.
Exercise
Write the signature of a function count_vowels that reads a piece of text without taking ownership, so callers can pass both a string literal and a String they still need afterwards. It returns the number of vowels as a usize.
Show answer
fn countvowels(text: &str) -> usize. The &str parameter accepts literals directly and accepts `&mystring` through deref coercion, and the caller keeps ownership.
Exercise
A caller writes let n = String::from("x"); let m = consume(n); println!("{n}"); where consume(s: String) -> String. Why does this fail, and name two ways to fix it.
Show answer
Passing n by value moves ownership into consume, so n is invalid afterwards. Fixes: change consume to take &String or &str and call it with &n, or pass n.clone() so the original stays valid. Using m instead of n in the println! also works.