Sub topic 10
Passing references to functions
This chapter assumes you know how ownership and moves work in basic terms, and that you can use let mut, Vec, and string slices. It shows how to give a function access to data without giving the data away.
Why pass a reference
Passing a value like a Vec<i32> to a function moves it. The caller can no longer use the variable. A reference lets the function borrow the value instead. The caller stays the owner and can use the data after the call.
Rust has two kinds of reference:
&Tis a shared reference. The function can read the value but not change it.&mut Tis a mutable reference. The function can read and change the value.
A worked example
fn push_twice(v: &mut Vec<i32>, x: i32) {
v.push(x);
v.push(x);
}
fn total(v: &[i32]) -> i32 {
v.iter().sum()
}
fn main() {
let mut numbers = vec![1];
push_twice(&mut numbers, 5);
println!("{}", total(&numbers));
}This prints 11. Three details matter here:
- The parameter type
&mut Vec<i32>says the function will change the vector. The caller must write&mut numbersand must have declared the variable withlet mut. totaltakes&[i32], a slice. Passing&numbersworks because Rust converts&Vec<i32>to&[i32]automatically (deref coercion).- After both calls,
numbersstill belongs tomain.
Prefer slices and `&str` in parameters
Take the most general borrowed type that does the job.
| Instead of | Use | Accepts |
|---|---|---|
| `&Vec<T>` | `&[T]` | vectors, arrays, and slices |
| `&String` | `&str` | `String` values and string literals |
A function that takes &[i32] works with &numbers, &[1, 2, 3], and &numbers[1..]. A function that takes &Vec<i32> accepts only the first.
The borrowing rules in practice
At any moment, a value can have either of these:
- any number of shared references, or
- exactly one mutable reference.
The compiler checks this at compile time, so a function that holds &mut cannot be raced by another reference.
Common errors
| Mistake | What the compiler reports |
|---|---|
| Passing `numbers` instead of `&numbers` | Type mismatch, or "borrow of moved value" if you use it later |
| Calling `push_twice(&numbers, 5)` | Expected `&mut Vec<i32>`, found `&Vec<i32>` |
| Calling `push_twice(&mut numbers, 5)` when `numbers` was declared with `let` | "Cannot borrow as mutable" |
| Keeping a shared reference alive while calling a `&mut` function | "Cannot borrow as mutable because it is also borrowed as immutable" |
| Returning a reference to a local variable | "Missing lifetime specifier" or "returns a reference to data owned by the current function" |
Choosing between value and reference
- Use
&Twhen the function only reads. - Use
&mut Twhen the function must change the caller's data. - Take the value itself when the function needs to own it, for example to store it in a struct or send it to another thread.
- Small
Copytypes such asi32andboolare normally passed by value. Copying them is as cheap as passing a reference.
Exercise
Write a function double_all that doubles every element of a vector of i32 in place, and call it from main so that the caller can still print the vector afterwards. What parameter type should it use, and how do you call it?
Show answer
Use &mut [i32] (or &mut Vec<i32>). For example: fn double_all(v: &mut [i32]) { for x in v.iter_mut() { *x *= 2; } }. In main, declare let mut nums = vec![1, 2, 3];, call double_all(&mut nums);, then println!("{:?}", nums); prints [2, 4, 6]. The caller keeps ownership because only a borrow was passed.
Exercise
Why does fn count(s: &str) -> usize accept both count("hi") and count(&my_string) when my_string is a String?
Show answer
A string literal already has type &str. For a String, &my_string has type &String, and Rust automatically converts it to &str through deref coercion at the call site.