Sub topic 8
Understanding borrow checker conflicts
This chapter assumes you can read a basic rustc diagnostic (error code, primary span, labels). It also assumes you know what & and &mut mean and how a move works. The aim is to explain why the borrow checker rejects a program, so you can pick a fix on purpose instead of by trial and error.
The rule behind the errors
At any point in a program, a value can have either of these:
- any number of shared references (
&T), or - exactly one mutable reference (
&mut T).
It cannot have both at once. Rust enforces this because mutation through one name can invalidate what another name sees. Nearly every borrow error is a violation of this rule.
Two things make the rule easier to apply:
- A borrow lasts from where it is created to its last use, not to the end of the enclosing block. This is called non-lexical lifetimes (NLL).
- The checker works on the whole function body. It reports the borrow, the conflicting access, and the later use that keeps the borrow alive.
E0502: shared borrow, then mutable borrow
This is the classic case from the topic's code examples:
fn main() {
let mut v = vec![1, 2, 3];
let first = &v[0];
v.push(4);
println!("{first}");
}rustc reports:
error[E0502]: cannot borrow `v` as mutable because it is also borrowed as immutable
--> src/main.rs:4:5
|
3 | let first = &v[0];
| - immutable borrow occurs here
4 | v.push(4);
| ^^^^^^^^^ mutable borrow occurs here
5 | println!("{first}");
| ------- immutable borrow later used hereThe diagnostic has three parts, and you need all three to fix the error:
- Where the first borrow starts (line 3).
- Where the conflicting access happens (line 4, the primary span).
- Where the first borrow is used again (line 5). This is the use that keeps the borrow alive.
The conflict is real. push may reallocate the vector's buffer, which would leave first pointing at freed memory. Remove or move the line 5 use and the error disappears:
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 the push. Its borrow has already ended, even though first is still in scope.
If you need the value after the push, copy it so you no longer hold a reference:
fn main() {
let mut v = vec![1, 2, 3];
let first = v[0];
v.push(4);
println!("{first} {v:?}");
}E0499: two mutable borrows
A second &mut while the first is still in use gives E0499:
fn main() {
let mut s = String::from("hi");
let a = &mut s;
let b = &mut s;
a.push('x');
b.push('y');
}The message is "cannot borrow s as mutable more than once at a time". The labels point at both borrows and at the later use of the first. Two mutable references to one value would let writes through one name surprise the other.
The fix is to make the uses sequential so the borrows don't overlap:
fn main() {
let mut s = String::from("hi");
let a = &mut s;
a.push('x');
let b = &mut s;
b.push('y');
println!("{s}");
}Here a is dead after its push, so b is free to borrow.
Related codes
The same rule produces several neighboring errors. The table shows how to recognize each one.
| Code | Situation | Typical fix |
|---|---|---|
| E0502 | Mutable borrow while a shared borrow is still used later | Use the shared borrow first, copy the data, or restructure |
| E0499 | Second mutable borrow while the first is still used later | Make the uses sequential |
| E0506 | Assigning to a value that is borrowed | Finish using the reference before assigning |
| E0505 | Moving a value while it is borrowed | Finish using the reference first, or clone before the move |
| E0596 | Taking `&mut` of a binding not declared `mut` | Add `mut` to the declaration or parameter |
E0596 connects this chapter to the previous one on immutable bindings. If the binding itself isn't mut, no &mut can be created, so check that first before thinking about overlap.
Common real-world shapes
Mutating a collection while iterating it
fn main() {
let mut v = vec![1, 2, 3];
for x in &v {
if *x == 2 {
v.push(10);
}
}
}The for loop holds a shared borrow of v for the whole loop. The push inside is E0502. Build the changes separately and apply them after the loop:
fn main() {
let mut v = vec![1, 2, 3];
let mut extra = Vec::new();
for x in &v {
if *x == 2 {
extra.push(10);
}
}
v.extend(extra);
println!("{v:?}");
}Borrowing one field, then calling a method on the whole struct
struct Counter {
items: Vec<i32>,
total: i32,
}
impl Counter {
fn bump(&mut self, by: i32) {
self.total += by;
}
}
fn main() {
let mut c = Counter { items: vec![1, 2, 3], total: 0 };
for x in &c.items {
c.bump(*x);
}
println!("{}", c.total);
}This fails with E0502. The loop borrows c.items, but c.bump borrows all of c mutably, and a method call hides which fields it touches. The compiler can track disjoint fields only when you name them directly:
struct Counter {
items: Vec<i32>,
total: i32,
}
fn main() {
let mut c = Counter { items: vec![1, 2, 3], total: 0 };
for x in &c.items {
c.total += *x;
}
println!("{}", c.total);
}Borrowing c.items and writing c.total touch different fields, so this is accepted. If you need the method, move the logic into a function that takes only the fields it needs, for example fn bump(total: &mut i32, by: i32).
Two mutable elements of one slice
Indexing twice with &mut v[0] and &mut v[1] is rejected, because the checker cannot prove the indices differ. The standard library provides a method that does the proof:
fn main() {
let mut v = vec![1, 2, 3];
let (left, right) = v.split_at_mut(1);
std::mem::swap(&mut left[0], &mut right[0]);
println!("{v:?}");
}Edge cases that confuse readers
Two-phase borrows let a call like this compile:
fn main() {
let mut v = vec![1, 2, 3];
v.push(v.len());
println!("{v:?}");
}The &mut v for push is reserved first but only activated after the arguments are evaluated, so v.len() can still read v. The same code with a stored let r = &mut v; before the call would fail. If an error looks like it should not exist, check whether a named reference is keeping a borrow alive across the line.
A borrow also stays alive through anything derived from it. If you call let s = v.iter() or let t = &v[1..], then s and t keep v borrowed until their last use. The diagnostic's "later used here" label points at the derived value, not at the original reference.
A decision procedure
The diagram summarizes how to choose a fix once you have read the three labels.
Prefer the options in this order: reorder, then restructure, then clone. Cloning makes the error go away, but it can hide a design problem and costs allocation. Use it when both places genuinely need their own copy.
When the error mentions lifetimes
If the "later used here" label points at a returned reference or a value stored in a struct, the conflict may come from a function signature. A function that returns a reference ties the output to its inputs, and the caller's input stays borrowed for as long as the result lives. The next chapter covers how to read and write those annotations.
Exercise
This program fails with E0502. Name the line that keeps the shared borrow alive, and give a fix that keeps the println! unchanged.
fn main() {
let mut names = vec![String::from("a"), String::from("b")];
let first = &names[0];
names.push(String::from("c"));
println!("{first}");
}
Show answer
The println!("{first}") line is the later use that keeps the shared borrow of names alive across the push. Clone the element so first owns its data: let first = names[0].clone();. Then no borrow of names exists when push runs, and the program compiles. Moving the push after the println! would also work, but it changes the statement order.
Exercise
In the Counter example, why does c.total += *x compile inside for x in &c.items, while c.bump(*x) does not?
Show answer
Naming c.total and c.items directly lets the compiler see that the two borrows touch different fields, so they do not overlap. c.bump(*x) borrows the whole c mutably, because the method signature takes &mut self and does not say which fields it uses. That overlaps with the shared borrow of c.items, which gives E0502.