Sub topic 9
The Borrowing Rules and the Borrow Checker
This chapter assumes you know how moves work, and that you can write &T and &mut T in function signatures. Here you will learn the rule the compiler checks for every reference, and how to read its errors.
The rules
At any point in the program, a value can have one of these:
- Any number of shared references (
&T). - Exactly one mutable reference (
&mut T).
A mutable reference and any other reference to the same value cannot be live together. This rules out two kinds of bugs at compile time: a data race, and a reference that points to data another reference just changed. A common example is growing a Vec while holding a pointer into it. The growth may move the buffer and leave the pointer dangling.
The borrow checker is the compiler pass that enforces these rules. It tracks every borrow from where it is created to where it is last used.
Borrows end at their last use
A borrow lasts until its last use, not until the end of the block. Rust calls this non-lexical lifetimes.
fn main() {
let mut v = vec![1, 2, 3];
let first = &v[0];
println!("{first}");
v.push(4);
println!("{:?}", v);
}This compiles because first is last used before push needs a mutable borrow. If you move the println!("{first}") line after the push, the shared borrow is still live when push runs, and compilation fails.
error[E0502]: cannot borrow `v` as mutable because it is also borrowed as immutable
| let first = &v[0];
| - immutable borrow occurs here
| v.push(4);
| ^^^^^^^^^ mutable borrow occurs here
| println!("{first}");
| -------- immutable borrow later used hereRead the message in three parts. It names the conflicting borrow, the new borrow, and the later use that keeps the first borrow alive. To fix it, end the first borrow earlier, or copy the data out first with let first = v[0];.
Common errors and fixes
| Error | Cause | Typical fix |
|---|---|---|
| E0499 | Two `&mut` borrows live at once | Finish using the first, or split the data |
| E0502 | `&mut` requested while `&` is live (or the reverse) | Shorten the shared borrow, or copy the value out |
| E0506 | Assigning to a value that is borrowed | Assign after the last use of the borrow |
| E0505 | Moving a value that is borrowed | Borrow instead of moving, or clone |
Mutating through one reference
The mutable borrow is exclusive, even when you only call one method on it.
fn add_suffix(s: &mut String) {
s.push_str(", world");
}
fn main() {
let mut s = String::from("hello");
add_suffix(&mut s);
println!("{s}");
}Passing &mut s borrows s only for the call. Afterwards s is usable again.
Exercise
This code fails to compile. Which rule does it break, and how do you fix it without changing what it prints? let mut s = String::from("a"); let r = &s; s.push('b'); println!("{r}");
Show answer
It requests a mutable borrow (push) while the shared borrow r is still live, because r is used afterwards. This breaks the rule that a mutable reference cannot coexist with other references. Move the println!("{r}") before s.push('b'), so the shared borrow ends first. Alternatively, drop r and print s after the push.