Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

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.

~5 min readRust
#Rust#Borrow Checker#Ownership#Debugging
3D diagram of one data cube with a shared arrow and an exclusive arrow crossing at the same point, headline E0502

Introduction & Quick Summary

Symptom. The borrow checker rejects a function that only reads:

code
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 here

Cause. 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:

rust
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:

rust
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:

bash
cargo check --message-format=short # one line per error, easier to scan rustc --explain E0502 # the official explanation, offline

rustc --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:

CodeMessageTypical trigger
E0502cannot borrow as immutable because it is also borrowed as mutable&mut element held while calling len
E0499cannot borrow as mutable more than once at a timeTwo &mut to one place, no overlap allowed
E0503cannot use x because it was mutably borrowed laterUse before a later &mut the compiler keeps live
E0505cannot move out of x because it is borrowedMoving a value while a reference is alive
E0506cannot assign to x because it is borrowedReassigning a borrowed place

Ways to satisfy the checker, and what each costs:

TechniqueFixesCost
Copy the value out first (let n = v.len())Reads of the containerCopy or clone
Scope the borrow in a blockAnything ending before the next borrowNone
split_at_mut(i)Two mutable elements at onceIndex arithmetic
iter_mut() / enumerate()The whole loop patternNone
drain(..) / retainRemoval while iteratingAllocation if collected
std::mem::take / replaceMoving out of a borrowed fieldA default value
RefCell<T>Anything elseRuntime 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:

rust
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:

rust
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:

rust
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:

rust
// 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:

rust
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:

rust
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: BorrowMutError

RefCell 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 &mut to 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.
  • RefCell as the first resort. Runtime panics in production replace build-time errors, and the stack trace names borrow_mut rather than your logic.
  • Indexing twice in one statement. v[i] = v[j] + 1 works because the reads and writes are sequenced; let a = &mut v[i]; v[i] = 1; does not, and splitting the index into a local i does not change that.
  • get_mut returning Option. let Some(a) = v.get_mut(0) keeps the borrow alive through the whole if let body; call len() before it, not inside.
  • HashMap two-step update. if let Some(v) = map.get_mut(&k) { ... } followed by map.insert(k, v) is two borrows; the entry API 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 edition in Cargo.toml first.
  • async blocks holding a borrow across await. The borrow lasts for the whole future, so a mutable borrow taken before await conflicts 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 documentation

The Rust documentation that defines the behaviour this guide explains.

Try matching browser tools

All tools

Small utilities that fit Rust work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Rust guides

More in Rust

All Rust guides

The guides filed next to this one in Rust, in library order.