Sub topic 10
Passing references to functions
This chapter assumes you can write and call a function with typed parameters, and that you know let versus let mut. It also assumes you know that String owns heap data while &str is a view into string data. The chapter covers how to let a function use a value without taking it, and how to choose between the parameter types that allow this.
Why functions borrow
Passing a value to a function by value moves it. After the call, the caller can no longer use the variable.
fn consume(s: String) -> usize {
s.len()
}
fn main() {
let name = String::from("Ferris");
let n = consume(name);
println!("{n}");
// println!("{name}"); // error[E0382]: borrow of moved value: `name`
}consume takes ownership of the String and drops it when it returns. The commented line would not compile because name was moved.
A reference lets the function use the value while the caller keeps ownership. The & operator creates a reference, and the act of creating one is called borrowing. The reference is valid only while the owner is alive and has not been moved.
Shared references: `&T`
A parameter of type &T is a shared (read-only) reference. The function can read through it, but it cannot modify or move out of the value.
fn total(v: &[i32]) -> i32 {
v.iter().sum()
}
fn main() {
let numbers = vec![1, 2, 3];
println!("{}", total(&numbers));
println!("{}", total(&numbers));
println!("{:?}", numbers);
}This prints 6, 6, and then [1, 2, 3]. The caller passes &numbers and can keep using numbers afterwards. Any number of shared references to the same value can exist at once. Shared references are also Copy, so passing one does not use it up.
Mutable references: `&mut T`
A parameter of type &mut T lets the function change the value in place. Both the variable and the reference must be declared mutable: the variable with let mut, and the call site with &mut.
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. The &mut at the call site is required. It tells the reader that numbers may change.
To replace the whole value behind a &mut T, or to write to a non-collection such as an integer, dereference with *:
fn bump(counter: &mut u32) {
*counter += 1;
}
fn double_all(values: &mut [i32]) {
for v in values.iter_mut() {
*v *= 2;
}
}
fn main() {
let mut hits = 0;
bump(&mut hits);
bump(&mut hits);
let mut data = [1, 2, 3];
double_all(&mut data);
println!("{hits} {:?}", data);
}The output is 2 [2, 4, 6]. Method calls such as v.push(x) dereference automatically. Plain assignment and arithmetic on the referenced value need an explicit *.
The borrowing rules
The compiler enforces two rules at every point in the program:
- You can have any number of shared references to a value, or exactly one mutable reference, but not both at the same time.
- A reference can never outlive the value it points to.
The first rule prevents data races and iterator invalidation, such as pushing to a vector while a function reads from it. It applies to arguments in a single call:
copy_into(&mut a, &a); // does not compile: error[E0502]Here copy_into(dst: &mut Vec<i32>, src: &Vec<i32>) would receive a mutable and a shared reference to the same Vec. The compiler rejects the call, because dst could change the data that src is reading. Pass two different vectors, or clone one of them.
A borrow ends at its last use, not at the end of the enclosing block. This is called non-lexical lifetimes. It is why this compiles:
fn main() {
let mut s = String::from("hi");
let r = &s;
println!("{r}");
s.push('!');
println!("{s}");
}The shared borrow r is last used in the first println!. The mutation afterwards is therefore allowed.
Choosing the parameter type
Prefer the most general borrowed type that does the job. The usual substitutions are:
| You want to accept | Parameter type | Why |
|---|---|---|
| Text, read-only | `&str` | Accepts `&String`, string literals, and slices of either |
| A list, read-only | `&[T]` | Accepts `&Vec<T>`, arrays, and sub-slices |
| A list whose items change | `&mut [T]` | No need for `&mut Vec<T>` unless you add or remove items |
| A list that grows or shrinks | `&mut Vec<T>` | Only `Vec` has `push` and `remove` |
| A value to keep or consume | `T` | The function takes ownership |
&String and &Vec<T> are almost always worse than &str and &[T]. The compiler converts &String to &str and &Vec<T> to &[T] automatically at call sites. This is called deref coercion. The slice types accept more callers.
fn shout(s: &str) -> String {
s.to_uppercase()
}
fn main() {
let owned = String::from("hello");
println!("{}", shout(&owned));
println!("{}", shout("world"));
println!("{}", shout(&owned[1..3]));
}The output is HELLO, WORLD, and EL. One function handles an owned String, a literal, and a slice.
For small Copy types such as i32, bool, and char, pass by value. A reference adds indirection and gains nothing. Use &mut only when the function must change the caller's value, and consider returning a new value instead when that reads more clearly.
Returning references
A function can return a reference, but only to data that outlives the call. That means data the caller passed in, or 'static data. The compiler must be able to tell which input the result borrows from. With a single reference parameter, it infers this automatically (lifetime elision):
fn first_word(s: &str) -> &str {
s.split_whitespace().next().unwrap_or("")
}
fn main() {
let line = String::from("borrow checker rocks");
let w = first_word(&line);
println!("{w}");
}The returned &str points into line, and the compiler treats it as a borrow of line. While w is in use, you cannot mutate or move line.
You cannot return a reference to a local variable:
fn make() -> &String { // does not compile: error[E0106]
let s = String::from("x");
&s // `s` is dropped when `make` returns
}The fix is to return the owned value, String, and let the caller own it.
With two or more reference parameters, elision cannot choose, and you must write lifetime annotations such as fn longest<'a>(a: &'a str, b: &'a str) -> &'a str. Lifetime annotations are beyond this chapter's scope. Treat the error as a request to say which input the result comes from.
Common errors
- Forgetting
&at the call site.total(numbers)passes aVecwhere a slice reference is expected, and the compiler reports a type mismatch. Add&. - Forgetting
mutin two places.push_twice(&mut numbers, 5)needslet mut numbers. Without it you get error E0596, "cannot borrow as mutable". - Holding a reference across a mutation. Keeping
first_word's result while callingline.clear()triggers E0502. Finish using the reference first, or copy it with.to_string(). - Assigning to the reference instead of the value.
counter += 1on a&mut u32does not compile. Write*counter += 1. - Moving out of a borrow. Given
s: &String, writinglet t: String = *s;fails with E0507, because a borrow cannot give up ownership. Uses.clone()if you need an owned copy.
Exercise
A function must append the text "!" to a caller's String and must not return anything. What should its signature be, and how does the caller invoke it on let mut msg = String::from("hi");?
Show answer
fn exclaim(s: &mut String) { s.push('!'); }, called as exclaim(&mut msg);. It needs &mut String because it grows the string, and a &str could not be changed. The variable must be declared mut, and the call site needs &mut.
Exercise
Why does this fail to compile, and what is the smallest fix?
fn longestlen(v: &Vec<String>) -> usize { v.iter().map(|s| s.len()).max().unwrapor(0) }
called as longest_len(&mut words) where words is declared let mut words = vec![String::from("a")]; — and the function then also needs to accept a plain array.
Show answer
The call itself compiles, because the compiler reborrows &mut Vec<String> as &Vec<String>. The real limitation is that &Vec<String> rejects arrays such as ["a".to_string()]. Change the parameter to v: &[String]. Then &words, &words[..], and &array all work, and the body is unchanged. Passing &mut for a read-only parameter is allowed but misleading, so prefer &words.