Looking for a structured path? Browse all Rust lessons.
- Maintained by
- Learning Platform content team
- Reviewed by
- Learning Platform source and executable-example contract
Fix Rust E0502: cannot borrow as mutable because it is also borrowed as immutable
The problem: E0502 means a shared reference (&value) is still in use at the point where you try to take a mutable one (&mut value, often implicitly through a method such as push). Rust allows many readers or one writer at a time, never both. The rule exists because a mutation can move or free the data the reader points at.
Reproduce the error
fn main() {
let mut queue = vec![String::from("build"), String::from("test")];
let first = &queue[0];
queue.push(String::from("deploy"));
println!("first job: {first}");
}
The compiler marks three places: the immutable borrow &queue[0], the mutable borrow inside queue.push(...), and the later use of first that keeps the shared borrow alive. push may reallocate the vector, which would leave first pointing at freed memory.
Preferred fix: finish reading before you mutate
fn main() {
let mut queue = vec![String::from("build"), String::from("test")];
let first = &queue[0];
println!("first job: {first}");
queue.push(String::from("deploy"));
println!("jobs queued: {}", queue.len());
}
Expected output:
first job: build
jobs queued: 3
A borrow lasts until its last use, not until the end of the block. Once first is printed, the shared borrow is over and push is allowed. Reordering is often the whole fix.
Other valid fixes
When you need the value after the mutation, take your own copy so no borrow is held. For Copy types such as integers, index without &; for String and other owned data, clone the single element you need:
fn main() {
let mut queue = vec![String::from("build"), String::from("test")];
let first = queue[0].clone();
queue.push(String::from("deploy"));
println!("first job: {first}");
println!("jobs queued: {}", queue.len());
}
Store an index instead of a reference when you want to look the element up again later. An index is a plain usize and holds no borrow.
Common failure mode: mutating a collection while iterating it
for job in &queue { queue.push(...) } produces the same E0502, because the loop holds a shared borrow for its whole duration. Collect the new items first, then extend the collection after the loop:
fn main() {
let mut queue = vec![String::from("build"), String::from("test")];
let follow_ups: Vec<String> = queue
.iter()
.map(|job| format!("{job}:verify"))
.collect();
queue.extend(follow_ups);
println!("{}", queue.join(", "));
}
Wrapping the data in RefCell to get past the compiler moves the same conflict to runtime, where it panics instead of failing to compile. Restructure the access first.
Run the failing and fixed versions in the Rust playground, review the borrowing rules in the borrowing lesson, then practice with vectors and maps in collections. For two overlapping mutable borrows, see our E0499 guide.