Cannot borrow as mutable more than once at a time
Quick Answer
Ensure the first mutable borrow goes out of scope before creating a second, or restructure to avoid needing two simultaneous mutable borrows.
Rust's borrow checker only allows one mutable reference (&mut T) to exist at a time. This error fires when a second mutable borrow is created while the first is still in scope.
- 1Holding a &mut reference across a loop iteration that also takes &mut
- 2Two &mut borrows of different fields of the same struct (before NLL)
- 3Passing &mut self while holding another &mut to a field
Fix 1
End the first borrow before starting the second
fn main() {
let mut v = vec![1, 2, 3];
{
let first = &mut v[0]; // first &mut borrow
*first = 10;
} // first borrow ends here
let second = &mut v[1]; // now safe — only one &mut
*second = 20;
}Why this works
Wrapping the first borrow in a block ensures it drops at the closing brace, before the second mutable borrow is created.
Fix 2
Use split_at_mut for disjoint indices
let mut v = vec![1, 2, 3, 4]; let (left, right) = v.split_at_mut(2); left[0] = 10; // &mut to v[0..2] right[0] = 30; // &mut to v[2..4] — disjoint, safe
Why this works
split_at_mut proves to the compiler that the two mutable slices are disjoint, allowing both to exist simultaneously.
let mut v = vec![1, 2, 3];
let a = &mut v;
let b = &mut v; // error[E0499]: cannot borrow v as mutable more than once
println!("{:?} {:?}", a, b);Rust Compiler Error Index
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev