Sub topic 8
Borrowing with mutable references
This chapter assumes you know shared references (&T), moves, and how String and Vec store data on the heap. Here you learn how to lend a value out so the borrower can change it.
Why a mutable reference exists
A shared reference lets you read a value but not change it. A mutable reference, written &mut T, lets the borrower modify the value without taking ownership. The owner keeps the value and gets it back, changed, when the borrow ends.
fn add_suffix(s: &mut String) {
s.push_str(", world");
}
fn main() {
let mut s = String::from("hello");
add_suffix(&mut s);
println!("{s}");
}This prints hello, world. Two things must line up:
- The variable must be declared
mut. Without it,&mut sis a compile error. - The call site must write
&mut s, and the parameter type must be&mut String. Both sides show that mutation can happen.
The exclusivity rule
At any moment, a value can have either of these:
- Any number of shared references.
- Exactly one mutable reference.
You cannot have both at once. A mutable reference is exclusive access, so nobody else can read or write the value while it is live.
fn main() {
let mut s = String::from("hello");
let r1 = &mut s;
// let r2 = &mut s; // error[E0499]: cannot borrow `s` as mutable more than once
r1.push('!');
println!("{r1}");
}The rule prevents data races and iterator invalidation. If you push to a Vec while another reference points into it, the Vec may reallocate and leave that reference pointing at freed memory. Rust rejects the program before it can run.
Borrows end at their last use
A borrow lasts until the reference is last used, not until the end of the block. This is called non-lexical lifetimes.
fn main() {
let mut s = String::from("hi");
let r1 = &s;
let r2 = &s;
println!("{r1} {r2}");
let r3 = &mut s;
r3.push_str(" there");
println!("{r3}");
}This compiles because r1 and r2 are never used after the println!. Their borrows have ended before r3 is created. If you printed r1 after creating r3, the compiler would report error E0502, which says you cannot borrow as mutable because it is also borrowed as immutable.
Common errors
| Error | Cause | Usual fix |
|---|---|---|
| E0499 | Two `&mut` borrows overlap | Finish using the first before creating the second |
| E0502 | A `&mut` borrow overlaps a `&` borrow | Move the last read of the shared reference earlier |
| E0596 | Borrowing a non-`mut` variable as mutable | Add `mut` to the declaration |
Passing mutable references along
Inside a function, you can reborrow a &mut parameter by passing it on. The original reference is unusable until the reborrow ends, then it works again.
Exercise
This code fails to compile: let mut v = vec![1, 2, 3]; let first = &v[0]; v.push(4); println!("{first}");. Which error category applies, and how do you fix it?
Show answer
It is E0502. first is a shared borrow that is still used after v.push(4) needs a mutable borrow. Fix it by printing first before the push, or by copying the value with let first = v[0];, since i32 is Copy.