Sub topic 14
Reading and Fixing Common Borrow Checker Errors
This chapter assumes you know the borrowing rules from earlier in the tutorial: shared references (&T), mutable references (&mut T), the "many readers or one writer" rule, and basic lifetimes. You should also be able to run cargo build and read its output.
Borrow checker errors look long, but they follow a fixed structure. Once you can read that structure, most errors take a minute to fix.
Anatomy of a borrow error
Every error has an error code (such as E0502), a one-line summary, and one or more labeled source spans. The spans tell you the story of the conflict. A typical error labels three places:
- Where the borrow or move started.
- Where the conflicting use happens.
- Where the original borrow is used later, which is why it is still alive.
The third label is the one people miss. The compiler is not complaining about the order of your lines. It is saying the first borrow is still needed after the conflict.
You can look up any code with rustc --explain E0502. The wording of messages changes between compiler versions, but the codes are stable.
E0382: use of moved value
This error means you used a value after ownership moved elsewhere. This program does not compile:
fn consume(s: String) {
println!("{s}");
}
fn main() {
let s = String::from("hi");
consume(s);
println!("{s}");
}The compiler reports borrow of moved value: s and points at the call consume(s). It also notes that String does not implement Copy. The usual fix is to change the function to borrow:
fn show(s: &str) {
println!("{s}");
}
fn main() {
let s = String::from("hi");
show(&s);
println!("{s}");
}Taking &str instead of String also lets callers pass string literals. Clone only when the function truly needs its own copy: consume(s.clone()).
E0502: shared and mutable borrows overlap
This is the error from the earlier example with a vector. It does not compile:
fn main() {
let mut v = vec![1, 2, 3];
let first = &v[0];
v.push(4);
println!("{first}");
}error[E0502]: cannot borrow `v` as mutable because it is also borrowed as immutableThe labels show that first borrows v, that v.push(4) needs a mutable borrow, and that first is used afterward. push may reallocate the buffer, which would leave first pointing at freed memory. That is the exact bug the rule prevents.
You have three common fixes:
- Reorder so the last use of the shared borrow comes before the mutation.
- Copy the value out if the type is
Copy. - Clone the data if you need it after the mutation.
fn main() {
let mut v = vec![1, 2, 3];
let first = v[0];
v.push(4);
println!("{first} {:?}", v);
}Here v[0] copies an i32, so no borrow remains.
The loop variant
The same error appears when you change a collection while iterating over it:
fn main() {
let mut v = vec![1, 2, 3];
for x in &v {
v.push(*x);
}
}The for loop holds a shared borrow for its whole duration. Build the new items first, then add them:
fn main() {
let mut v = vec![1, 2, 3];
let extra: Vec<i32> = v.iter().map(|x| x * 10).collect();
v.extend(extra);
println!("{:?}", v);
}E0499: two mutable borrows
Only one &mut to a value may be alive at a time. This does not compile:
fn main() {
let mut s = String::from("a");
let a = &mut s;
let b = &mut s;
a.push('x');
b.push('y');
}The compiler says cannot borrow s as mutable more than once at a time, and its labels point at both borrows and at the later use of a. If you finish with a before creating b, the borrows no longer overlap and the code compiles. This works because of non-lexical lifetimes (NLL), which end a borrow at its last use.
fn main() {
let mut s = String::from("a");
let a = &mut s;
a.push('x');
let b = &mut s;
b.push('y');
println!("{s}");
}A related case is two &mut into one collection, such as &mut v[0] and &mut v[1]. The compiler cannot prove the indices differ. Use v.split_at_mut(1) to get two non-overlapping mutable slices.
E0596: cannot borrow as mutable
This error is about missing mut, not about overlapping borrows. There are two forms.
The first form is a variable that was not declared mut. The second form is a reference whose type is & instead of &mut:
fn add_bang(s: &String) {
s.push('!');
}
fn main() {
let s = String::from("hi");
add_bang(&s);
}The message is cannot borrow *s as mutable, as it is behind a & reference. The fix needs changes in three places: the parameter type, the call site, and the variable declaration.
fn add_bang(s: &mut String) {
s.push('!');
}
fn main() {
let mut s = String::from("hi");
add_bang(&mut s);
println!("{s}");
}E0505: moving out while borrowed
This error is the move counterpart of E0502. You cannot move a value while a reference to it is still going to be used.
fn main() {
let s = String::from("a");
let r = &s;
let t = s;
println!("{r} {t}");
}The message is cannot move out of s because it is borrowed. If t only needs to read the data, make it a reference too. If it needs ownership, use r before the move or clone: let t = s.clone();.
E0597: borrowed value does not live long enough
This error means the owner is dropped while a reference to it is still in use.
fn main() {
let r;
{
let x = 5;
r = &x;
}
println!("{r}");
}The labels say that x is dropped at the closing brace while r is used later. Move the owner to an outer scope:
fn main() {
let x = 5;
let r = &x;
println!("{r}");
}In real code this often shows up when a reference is pushed into a collection that outlives the data. The fix is the same. Either make the owner live as long as the collection, or store owned values in the collection.
E0106: missing lifetime specifier
You get this when a function returns a reference and the compiler cannot work out which input it borrows from. The classic case is returning a reference to a local variable:
fn dangle() -> &String {
let s = String::from("temp");
&s
}
fn main() {
let _r = dangle();
}The message says missing lifetime specifier and adds a help note about there being no value to borrow from. Adding a lifetime annotation cannot fix this, because s is dropped at the end of the function. Return the owned value:
fn make() -> String {
String::from("temp")
}
fn main() {
println!("{}", make());
}E0106 can also mean a real annotation is missing, as with a function that takes two reference parameters and returns one. Then you add 'a to the inputs and the output, as in longest<'a>. First ask whether the data comes from an input. If it does, annotate it. If it is created inside the function, return an owned value.
E0507: cannot move out of a borrow
You cannot take ownership of something you only borrowed, including an element of a vector.
fn main() {
let v = vec![String::from("a")];
let first = v[0];
}The message is cannot move out of index of Vec<String>. Indexing gives you a place inside the vector, and moving out would leave a hole. Choose what you actually need:
fn main() {
let v = vec![String::from("a"), String::from("b")];
let borrowed = &v[0];
let copied = v[1].clone();
println!("{borrowed} {copied}");
}If you really want to take the element out, use v.remove(0) or std::mem::take(&mut v[0]), which swaps in a default value.
A repeatable workflow
- Read only the first error. Later errors are often side effects of it.
- Find the three labels: where the borrow starts, where the conflict is, and where the borrow is used again.
- Decide which of the two conflicting uses can move. The most common fix is shortening a borrow by moving its last use earlier.
- Prefer restructuring over cloning. A clone is a fine fix when the cost is small, but it should be a choice you can explain.
- Rebuild after each fix.
Summary table
| Code | Plain meaning | First fix to try |
|---|---|---|
| E0382 | Used after a move | Borrow instead of moving |
| E0502 | Shared and mutable borrows overlap | Finish using the shared borrow first |
| E0499 | Two `&mut` at once | Use them one after another |
| E0596 | Mutating through `&` or a non-`mut` binding | Add `mut` or `&mut` |
| E0505 | Moved while borrowed | Use the borrow first, or clone |
| E0597 | Owner dropped too early | Declare the owner in an outer scope |
| E0106 | Compiler cannot pick a lifetime | Annotate, or return an owned value |
| E0507 | Moved out of a borrow | Borrow the element or clone it |
Exercise
This program fails with E0502. Explain which line holds the shared borrow, which line needs the mutable borrow, and give one fix that keeps the program's output the same. fn main() { let mut names = vec![String::from("Ana"), String::from("Bo")]; let first = &names[0]; names.push(String::from("Cy")); println!("{first}"); }
Show answer
The line let first = &names[0]; creates the shared borrow, and names.push(...) needs a mutable borrow while first is still used by the final println!. One fix is to clone the element: let first = names[0].clone();. Then first owns its data, no borrow of names remains, and the program prints Ana. Another fix is to move the println!("{first}"); line above the push call.
Exercise
A function fn pick() -> &str creates a String inside and returns a reference to it. Adding <'a> does not help. Why, and what should the signature be?
Show answer
The String is a local value dropped when the function returns, so any reference to it would dangle. A lifetime annotation only describes how long data lives and cannot extend it. Return the owned value: fn pick() -> String.