Sub topic 14
Reading and fixing common borrow checker errors
This chapter assumes you know shared and mutable references, the "many readers or one writer" rule, and basic lifetimes. You will learn to read a borrow checker error and pick a fix from a short list.
Anatomy of an error
Every borrow error has the same parts: an error code such as E0502, a one-line summary, and labeled spans. The spans show where a borrow starts, where the conflicting use happens, and where the first borrow is used later. Read the spans in that order. The fix usually means shortening the first borrow or changing who owns the data.
E0502: shared borrow, then mutation
fn main() {
let mut v = vec![1, 2, 3];
let first = &v[0];
v.push(4);
println!("{first}");
}The compiler reports "cannot borrow v as mutable because it is also borrowed as immutable". push may reallocate the buffer, which would leave first pointing at freed memory. Because i32 is Copy, you can copy the value out instead of borrowing it:
fn main() {
let mut v = vec![1, 2, 3];
let first = v[0];
v.push(4);
println!("{first}");
}E0499: two mutable borrows
fn main() {
let mut s = String::from("a");
let a = &mut s;
let b = &mut s;
a.push('x');
b.push('y');
}The error says "cannot borrow s as mutable more than once at a time". Both a and b are used later, so their lifetimes overlap. Finish with one reference before creating the next:
fn main() {
let mut s = String::from("a");
let a = &mut s;
a.push('x');
let b = &mut s;
b.push('y');
println!("{s}");
}E0382: use after move
fn consume(s: String) {
println!("{s}");
}
fn main() {
let s = String::from("hi");
consume(s);
println!("{s}");
}The message is "borrow of moved value: s". The compiler usually adds a note pointing at the parameter that took ownership. If consume only reads the string, change its parameter to &str and call consume(&s). If it needs its own copy, call consume(s.clone()).
E0106: missing lifetime specifier
fn dangle() -> &String {
let s = String::from("temp");
&s
}The compiler asks for a lifetime, but adding one would not help. The value s is dropped when the function ends, so no lifetime can make the reference valid. Return the owned value instead:
fn no_dangle() -> String {
String::from("temp")
}
fn main() {
println!("{}", no_dangle());
}A related error is E0597, "borrowed value does not live long enough". It means a reference outlives the variable it points to. Declare the variable in the outer scope, or return an owned value.
Choosing a fix
| Error | Typical cause | First fix to try |
|---|---|---|
| E0502 | Mutating while a shared borrow is still used later | Use the borrow earlier, or copy the value out |
| E0499 | Two live `&mut` to the same value | Finish with the first before taking the second |
| E0382 | Value moved, then used | Borrow instead, or `clone()` |
| E0106 | Returned reference has no clear source | Return an owned value, or add a lifetime tied to an input |
| E0597 | Reference outlives its owner | Move the owner to an outer scope |
Exercise
The code let first = &v[0]; v.push(4); println!("{first}"); fails with E0502. Why does moving the println! above v.push(4) make it compile?
Show answer
With non-lexical lifetimes, a shared borrow ends at its last use. If first is last used before push, the borrows no longer overlap, so the mutable borrow needed by push is allowed.