Rust E0502: cannot borrow as immutable because it is also borrowed as mutable
An element borrow is a borrow of the whole container. End the borrow before reading, take disjoint borrows with split_at_mut, and keep RefCell for cases that truly need it.

Introduction & Quick Summary
Symptom. The borrow checker rejects a function that only reads:
error[E0502]: cannot borrow `queue` as immutable because it is also borrowed as mutable
--> src/lib.rs:9:30
|
8 | let head = &mut queue[0];
| ------------ mutable borrow occurs here
9 | if queue.len() > 1 {
| ^^^^^ immutable borrow occurs here
10| head.count += 1;
| ---- first borrow later used hereCause. A mutable borrow of an element is still alive when the container is borrowed again. &mut queue[0] borrows the whole queue mutably for as long as head is used, not just one slot — indexing is a place expression, and the slice header it goes through is shared. Any &self method (len, iter, Display) needs an immutable borrow of the same container, and the two cannot coexist.
Fix. End the mutable borrow before the read (scope it, or copy the value you need), or take both borrows in a way the compiler can prove disjoint (split_at_mut, iter_mut, drain). Restructuring is almost always better than RefCell; interior mutability moves the same conflict to runtime, where it panics instead of failing the build.
Core Mechanics, Signatures & Reproducible Setup
Rust's borrow rules are enforced per place, with a borrow lasting from creation to last use (non-lexical lifetimes). The error appears when two borrows of the same place overlap in a way that crosses mutable and immutable access.
A minimal reproduction:
fn bump_first(queue: &mut Vec<Counter>) {
let head = &mut queue[0]; // mutable borrow of queue starts
if queue.len() > 1 { // E0502: immutable borrow of queue
head.count += 1;
}
}
struct Counter { count: u32 }The same code works when the read happens before the borrow, which is usually the correct program anyway:
fn bump_first(queue: &mut Vec<Counter>) {
let len = queue.len(); // immutable borrow ends here
if len > 1 {
queue[0].count += 1; // one mutable borrow, no overlap
queue[1].count += 1;
}
}Two useful tools while working through a borrow error:
cargo check --message-format=short # one line per error, easier to scan
rustc --explain E0502 # the official explanation, offlinerustc --explain is worth running before restructuring: it names the canonical fixes for that exact code, and E0502, E0499, E0503 and E0505 read alike in a terminal.
Key Comparison Table
The borrow-checker errors that get confused with each other:
| Code | Message | Typical trigger |
|---|---|---|
| E0502 | cannot borrow as immutable because it is also borrowed as mutable | &mut element held while calling len |
| E0499 | cannot borrow as mutable more than once at a time | Two &mut to one place, no overlap allowed |
| E0503 | cannot use x because it was mutably borrowed later | Use before a later &mut the compiler keeps live |
| E0505 | cannot move out of x because it is borrowed | Moving a value while a reference is alive |
| E0506 | cannot assign to x because it is borrowed | Reassigning a borrowed place |
Ways to satisfy the checker, and what each costs:
| Technique | Fixes | Cost |
|---|---|---|
Copy the value out first (let n = v.len()) | Reads of the container | Copy or clone |
| Scope the borrow in a block | Anything ending before the next borrow | None |
split_at_mut(i) | Two mutable elements at once | Index arithmetic |
iter_mut() / enumerate() | The whole loop pattern | None |
drain(..) / retain | Removal while iterating | Allocation if collected |
std::mem::take / replace | Moving out of a borrowed field | A default value |
RefCell<T> | Anything else | Runtime BorrowMutError risk |
Practical Edge Cases, Error Fixes & Deep Dive Code Examples
1. Scoping the mutable borrow
The simplest fix is a block that ends the borrow before the next read. The compiler ends a borrow at last use, so extracting the work into a scope is enough:
fn normalize(items: &mut [Item], limit: usize) {
{
let first = &mut items[0];
first.score = first.score.min(limit);
} // mutable borrow ends
if items.len() > 1 {
items[1].score = items[1].score.min(limit);
}
}If the borrow must survive, the container cannot be read at all in that region. Decide which of the two you actually need; most E0502s are a program that read len mid-mutation because a bounds check happened to sit there.
2. Two mutable elements at once
&mut v[0] and &mut v[1] are two mutable borrows of v, so E0499 or E0502 depending on order. split_at_mut hands out two disjoint mutable slices, and the compiler accepts the proof:
fn swap_ends(v: &mut [u32]) {
let (left, right) = v.split_at_mut(1);
std::mem::swap(&mut left[0], &mut right[right.len() - 1]);
}
fn increment_pairs(pairs: &mut [(u32, u32)]) {
for (a, b) in pairs.iter_mut() {
*a += 1;
*b += *a; // reads *a through the same &mut, fine
}
}iter_mut is the better answer whenever the problem is "inside a loop", because each iteration yields an exclusive reference with no shared borrow of the container.
3. Calling a &self method on the element's owner
A method call on the container is an immutable borrow even when it looks like it only inspects one field:
struct Buffer { data: Vec<Vec<u8>> }
impl Buffer {
fn total(&self) -> usize { self.data.iter().map(Vec::len).sum() }
// E0502: self.total() while the inner borrow is alive
fn push_to_last(&mut self, byte: u8) {
let last = self.data.last_mut().unwrap();
let new_total = self.total(); // immutable borrow of self
last.push(byte);
println!("{new_total}");
}
}Computing the total before taking the mutable reference, or after the mutation ends, removes the overlap. This is also where RefCell tempts people; an owned usize computed at the right moment is cheaper and cannot panic.
4. Removing elements while iterating
An index loop that removes from the same Vec inside the body is the most common real-world E0502, and the fix is an iterator that owns the removal:
// Broken: remove while a shared borrow from indexing is considered alive
fn prune(v: &mut Vec<Job>) {
for i in 0..v.len() {
if v[i].done {
v.remove(i); // panic risk and borrow friction
}
}
}
// Fixed A: retain, one pass, no index arithmetic
fn prune(v: &mut Vec<Job>) {
v.retain(|job| !job.done);
}
// Fixed B: drain into a new vector when you need the removed values
fn take_done(v: &mut Vec<Job>) -> Vec<Job> {
let mut done = Vec::new();
v.retain(|job| {
if job.done { done.push(job.clone()); false } else { true }
});
done
}retain also avoids the skipped-element bug of the index version, where removing shifts the next element into the slot just visited.
5. Closures that capture the container again
The classic async or callback shape: a closure borrows the vector while the outer loop borrows it mutably. Since the 2021 edition, closures capture individual fields rather than the whole struct, which fixes some of these automatically:
struct Store { items: Vec<Item>, hits: u32 }
impl Store {
fn touch_all(&mut self) {
let hits = &mut self.hits; // disjoint field borrow
self.items.iter_mut().for_each(|item| {
item.touched = true;
*hits += 1; // no borrow of self.items here
});
}
}If the closure truly needs the whole struct, split the work: collect the mutations, then apply them after the iteration ends. Moving the closure's work into a free function that takes &mut Item and &mut u32 is the smallest change that compiles.
6. When RefCell is the honest answer
Interior mutability is legitimate for graphs, caches behind a shared handle, and observer lists — but it converts a compile error into a runtime panic:
use std::cell::RefCell;
let cell = RefCell::new(vec![1, 2, 3]);
let a = cell.borrow_mut();
let b = cell.borrow(); // panics: already mutably borrowed: BorrowMutErrorRefCell gives no protection against the same overlap, only a later detection. If the data is shared across threads, the equivalent is Mutex (blocking) or RwLock, and the same rule applies: drop the guard before taking the next one.
Common Compilation/Runtime Mistakes & Version Gotchas
- Adding
&mutto a function signature to silence a call site. Moving the error to the caller is legitimate only when the function truly mutates; otherwise it spreads the borrow for no reason. clone()to escape E0502. It compiles and hides a design issue; on a hot loop it is also the difference between O(1) and O(n) per iteration. Clone after the borrow restructuring, not before it.RefCellas the first resort. Runtime panics in production replace build-time errors, and the stack trace namesborrow_mutrather than your logic.- Indexing twice in one statement.
v[i] = v[j] + 1works because the reads and writes are sequenced;let a = &mut v[i]; v[i] = 1;does not, and splitting the index into a localidoes not change that. get_mutreturningOption.let Some(a) = v.get_mut(0)keeps the borrow alive through the wholeif letbody; calllen()before it, not inside.- HashMap two-step update.
if let Some(v) = map.get_mut(&k) { ... }followed bymap.insert(k, v)is two borrows; theentryAPI does it in one. - Edition differences. 2021 changed closure capture to disjoint fields, and 2024 tightens temporary lifetimes in tail expressions, so the same code can produce E0502 under one edition and compile under another. Check
editioninCargo.tomlfirst. asyncblocks holding a borrow acrossawait. The borrow lasts for the whole future, so a mutable borrow taken beforeawaitconflicts with anything after it; restructure so the borrow ends before the await point.
Related tools. Put the failing function and the version that compiles side by side in the text diff tool to see whether the borrow moved or a clone crept in, and keep rustc --explain E0502 output in the commit message when the restructuring is non-obvious.
Official references
primary documentationThe Rust documentation that defines the behaviour this guide explains.
Try matching browser tools
All toolsSmall utilities that fit Rust work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Rust guides
All Rust guidesE0499: Cannot Borrow as Mutable More Than Once in Async Closures
An async block or FnMut closure keeps a mutable borrow alive past the point you expected. Scoping, split_at_mut and the Arc<Mutex> decision.
Rust Tokio: Blocking the Runtime and spawn_blocking Fixes
A synchronous call inside an async fn stops the worker that drives every other task on it, timers included. Detection, spawn_blocking, and the guard-across-await trap.
Rust: Future Cannot Be Sent Between Threads Safely in Tokio
spawn needs Send + 'static, and any non-Send value alive across an await breaks it. Shorten the guard, switch the lock, or move the work to a LocalSet.
Rust Unsafe: Raw Pointers, FFI Bindings, and Soundness Invariants
What unsafe actually unlocks, the five soundness contracts behind raw pointers, and the FFI rules for repr(C), CString and unwinding.
More in Rust
All Rust guidesThe guides filed next to this one in Rust, in library order.