Sub topic 8
Understanding borrow checker conflicts
This chapter assumes you can read a basic rustc diagnostic, know what a move is, and have seen & and &mut references. Here you learn why the borrow checker rejects some programs and how to rewrite them so it accepts them.
The rule behind the errors
At any moment, a value can have either of these:
- any number of shared references (
&T), or - exactly one mutable reference (
&mut T).
A mutable reference cannot coexist with any other reference to the same value. Two errors come from breaking this rule:
| Code | Meaning |
|---|---|
| E0502 | A mutable borrow was requested while a shared borrow is still in use. |
| E0499 | A second mutable borrow was requested while the first is still in use. |
The key phrase is "still in use". A borrow lasts from where it is created to its last use, not to the end of the scope. This is called non-lexical lifetimes.
A conflict you can read
fn main() {
let mut v = vec![1, 2, 3];
let first = &v[0];
v.push(4);
println!("{first}");
}cargo check reports E0502. The diagnostic has three labels:
let first = &v[0];is labeled as the immutable borrow.v.push(4);is labeled as the mutable borrow.println!("{first}");is labeled as where the immutable borrow is used later.
The third label is the one that matters most. The conflict exists only because first is used after the push. Also, push may reallocate the vector's memory. If it did, first would point at freed memory. The rule prevents that bug.
Three ways to fix it
Pick the fix that matches what you actually need.
- End the borrow before the mutation. Copy the value, or move the use earlier.
- Reorder the code so the last use of the reference comes before the mutable operation.
- Clone the data when you need an independent copy.
fn main() {
let mut v = vec![1, 2, 3];
let first = v[0]; // copies the i32, no borrow remains
v.push(4);
println!("{first}");
}Here v[0] copies an i32, so no reference is alive during push. The reordering fix works too. Print first before calling push, and the borrow ends in time.
Two mutable borrows (E0499)
fn main() {
let mut s = String::from("hi");
let a = &mut s;
let b = &mut s;
a.push('!');
b.push('?');
println!("{s}");
}rustc points at the first &mut s and the second &mut s, and says the first is later used. To fix it, finish with one borrow before starting the next:
fn main() {
let mut s = String::from("hi");
let a = &mut s;
a.push('!');
let b = &mut s;
b.push('?');
println!("{s}");
}The borrow in a ends after a.push('!'), so b is allowed.
Where borrows hide
Conflicts often come from borrows you did not write explicitly:
- Method calls such as
v.iter()borrowvfor the whole loop. - Calling
&mut selfmethods while holding a reference from a&selfmethod. - Looping over a collection and modifying it inside the loop.
fn main() {
let mut scores = vec![1, 2, 3];
for s in &scores {
if *s > 1 {
scores.push(*s);
}
}
}The loop holds a shared borrow of scores until it finishes, so push fails with E0502. A common fix is to collect the changes first, then apply them:
fn main() {
let mut scores = vec![1, 2, 3];
let extra: Vec<i32> = scores.iter().filter(|s| **s > 1).copied().collect();
scores.extend(extra);
println!("{scores:?}");
}Exercise
Why does this code fail with E0502, and what is the smallest change that fixes it? let mut s = String::from("a"); let r = &s; s.push('b'); println!("{r}");
Show answer
r is a shared borrow of s that is still used by println! after s.push('b') needs a mutable borrow. Move the println!("{r}"); line before s.push('b');, so the borrow ends before the mutation. Cloning s into r would also work.