E0502: cannot borrow as mutable because it is also borrowed as immutable
Rust allows either many readers or one writer, never both at once. If a shared `&` reference is still in use, taking a `&mut` would let the value change underneath the reader.
That rule is what makes iterator invalidation and data races impossible in safe Rust — the same bug class that causes crashes in C++ and surprising behaviour in Python.
Code that triggers it
fn main() {
let mut items = vec![1, 2, 3];
let first = &items[0]; // shared borrow starts here
items.push(4); // error[E0502]: needs a mutable borrow
println!("{first}"); // shared borrow still alive
}Code that compiles
fn main() {
let mut items = vec![1, 2, 3];
let first = items[0]; // copy the value out, borrow ends
items.push(4);
println!("{first}");
}End the shared borrow before mutating: copy the value out, or move the mutation into a separate scope. For integers a plain copy is free; for larger data, restructure so reads and writes do not overlap.
Try both versions
The broken version is loaded below so you can see the real compiler message, then fix it yourself.
Contrast AAA · 16.6:1
15px