Cannot borrow as mutable because also borrowed as immutable
Quick Answer
End the immutable borrow before creating the mutable borrow, or copy the value from the immutable borrow so the reference is no longer needed.
A value is borrowed immutably (&T) and then an attempt is made to also borrow it mutably (&mut T) while the immutable borrow is still alive. Rust prevents this to guarantee that immutable references see stable data.
- 1Holding a slice reference (&v[0]) and then pushing to the Vec
- 2Passing &self to a method while holding a &mut self reference
- 3Storing a reference to a Vec element and then modifying the Vec
Fix 1
Copy the value out of the immutable borrow before mutating
fn main() {
let mut v = vec![1, 2, 3];
let first = v[0]; // copy the i32 value, not a reference
v.push(4); // safe — no live immutable borrow
println!("{}", first);
}Why this works
For Copy types (i32, f64, bool…), indexing copies the value rather than borrowing it, leaving no live reference that could conflict with a mutable borrow.
Fix 2
Clone the needed data before mutating
let first = v[0].clone(); // for non-Copy types
v.push(expensive_item);
println!("{:?}", first);Why this works
clone() produces an independent owned copy, ending the dependency on the immutable borrow.
let mut v = vec![1, 2, 3];
let first = &v[0]; // immutable borrow
v.push(4); // error[E0502]: cannot borrow v as mutable because also borrowed as immutable
println!("{}", first);// error[E0502]: cannot borrow `v` as mutable because it is also borrowed as immutable
// --> src/main.rs:3:5
// |
// 2 | let first = &v[0];
// | - immutable borrow occurs here
// 3 | v.push(4);
// | ^^^^^^^^^ mutable borrow occurs here
// 4 | println!("{}", first);
// | ----- immutable borrow later used hereRust Compiler Error Index
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev