Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Rust E0499: cannot borrow as mutable more than once

Two live mutable borrows overlap. End the first one, split fields or slices, iterate by index, or move to RefCell only when runtime checks are honest.

~4 min readRust
#Rust#Borrow Checker#Ownership#Errors
A Rust value crate claimed by two cyan mutable arrows, an amber borrow token and a split gate beside it

Introduction & Quick Summary

text
error[E0499]: cannot borrow `data` as mutable more than once at a time --> src/main.rs:7:13 | 6 | let first = &mut data; | --------- first mutable borrow occurs here 7 | let second = &mut data; | ^^^^^^^^^^^ second mutable borrow occurs here 8 | first.push(1); first.push(2);

The borrow checker enforces one mutable reference at a time. Two live &mut to the same value would allow aliasing writes, which Rust rules out statically. E0499 is that rule, applied to a borrow that has not ended yet.

Split the three cases before choosing a fix:

  • The borrows do not overlap in time — end the first one with a scope, a block, or by not keeping it alive.
  • They touch different parts of a structure — split fields into separate bindings, or use split_at_mut on slices.
  • They really must alias at runtime — RefCell, Cell, or an arena with indices, in that order of preference.
PatternCompilesCostUse when
Sequential borrowsYesNoneSecond use starts after the first ends
Split fields into localsYesNoneMethod needs two fields
split_at_mutYesNoneTwo halves of one slice
RefCell<T>YesRuntime check, panic on conflictGraph-like structures
Cell<T> for CopyYesNoneCounters, flags
Index-based loopYesBounds checksMutating a collection while iterating

Core Mechanics, Signatures & Reproducible Setup

A borrow lives from the point it is created to its last use — not to the end of its enclosing scope. Non-lexical lifetimes (NLL, stable since 2018) shortened that window, which is why many snippets that "should" fail compile fine. E0499 reports two borrows whose live ranges overlap.

The signature that produces it is any function taking &mut self or &mut T while another &mut to the same value exists:

rust
fn main() { let mut data = vec![1, 2, 3]; let first = &mut data; first.push(4); let second = &mut data; // ok: `first` is dead here second.push(5); }
rust
fn main() { let mut data = vec![1, 2, 3]; let first = &mut data; let second = &mut data; // E0499: `first` still used later first.push(4); second.push(5); }

The second snippet fails because both borrows are used after the second is created. The diagnostic shows the three-line window precisely; the fix is to shorten one of them, not to invent a third reference.

Key Comparison Table

SituationWrongRight
Two sequential mutationsTwo live &mutOne &mut, then re-borrow
Two fields of one struct&mut self.a and &mut self.b through a methodDestructure: let Self { a, b, .. } = &mut self
Two halves of a slice&mut v[..n] and &mut v[n..]let (l, r) = v.split_at_mut(n)
Iterate and pushfor x in &mut v { v.push(x) }Collect first, or iterate by index
Shared graph nodesTwo &mut to the same nodeRc<RefCell<Node>>
Two entries of a HashMapget_mut twiceget_many_mut, or entry
Error codeMeaningTypical fix
E0499Two mutable borrows overlapShorten or split
E0502Mutable borrow while immutable existsEnd the shared borrow
E0506Assign while borrowedReorder
E0596Cannot borrow as mutableAdd mut or change ownership

Practical Edge Cases, Error Fixes & Deep Dive Code Examples

Case 1: Use the borrow, then let it end

rust
let mut items = vec![1, 2, 3]; let len = items.len(); // immutable borrow, ends immediately let r = &mut items; // fine now r.push(len);

The frequent failure is holding a borrow across a call that needs another:

rust
let mut map = std::collections::HashMap::new(); map.insert("a", 1); let value = map.get_mut("a").unwrap(); map.insert("b", 2); // E0499 *value += 1;

Move the second insert above the borrow, or scope the borrow:

rust
{ let value = map.get_mut("a").unwrap(); *value += 1; } map.insert("b", 2);

Case 2: Two fields need mutation at once

rust
struct Stats { total: u64, count: u64, } impl Stats { fn record(&mut self, v: u64) { let total = &mut self.total; let count = &mut self.count; *total += v; *count += 1; } }

That compiles — distinct fields are disjoint places. It stops compiling when the work moves into a method taking &mut self:

rust
impl Stats { fn bump(&mut self) { self.count += 1; } fn record(&mut self, v: u64) { self.total += v; self.bump(); // fine: sequential borrows } }
rust
fn bad(&mut self) { let total = &mut self.total; self.bump(); // E0499: `self` borrowed while `total` lives *total += 1; }

Bind the value, call the method, then write back, or destructure self so the compiler sees disjoint paths.

Case 3: Splitting a slice

rust
fn fill_both(v: &mut [u8], left: u8, right: u8) { let mid = v.len() / 2; let (a, b) = v.split_at_mut(mid); a.fill(left); b.fill(right); }

split_at_mut returns two &mut halves with non-overlapping ranges, which is the only safe way to hold them at once. get_many_mut does the same for a Vec with an array of indices, returning None if any index repeats.

Case 4: Iterating and mutating

rust
let mut v = vec![1, 2, 3]; for x in &mut v { v.push(*x); // E0499: `v` borrowed by the iterator }

The iterator holds &mut v for the whole loop. Decide what the loop means: append each element once, then either iterate over a snapshot or index explicitly.

rust
let n = v.len(); for i in 0..n { let x = v[i]; v.push(x); }

iter_mut is still the right tool when only elements change:

rust
for x in &mut v { *x *= 2; }

Case 5: A method that needs two elements

rust
impl Graph { fn connect(&mut self, from: usize, to: usize) { let a = &mut self.nodes[from]; let b = &mut self.nodes[to]; // E0499 a.edges.push(to); b.edges.push(from); } }

Two indices into one Vec cannot be borrowed mutably twice through IndexMut. Options, in order: use an adjacency list of ids only (self.edges[from].push(to), two separate statements), split with get_many_mut, or store nodes in a slotmap.

rust
self.edges[from].push(to); self.edges[to].push(from);

Two statements, two short borrows, no conflict.

Case 6: When runtime checking is the honest answer

rust
use std::cell::RefCell; use std::rc::Rc; type NodeRef = Rc<RefCell<Node>>; struct Node { value: i32, next: Option<NodeRef>, } fn link(a: &NodeRef, b: &NodeRef) { a.borrow_mut().next = Some(Rc::clone(b)); }

RefCell moves the check to runtime: borrow_mut while another borrow or borrow_mut is live panics. That panic is preferable to an incorrect program, but it is not free — keep RefCell at the boundary of a data structure rather than sprinkled through logic, and prefer index-based ownership models for large graphs.

Common Compilation/Runtime Mistakes & Version Gotchas

  • Cloning to silence the error. data.clone() compiles and changes semantics: the second write goes to a copy. Sometimes correct, usually a bug that no compiler will catch.
  • Rc<RefCell<_>> everywhere. It trades a compile-time guarantee for panics and reference-count overhead; prefer owned indices in trees and graphs.
  • RefCell borrow held across a call. let n = node.borrow_mut(); other(&n); panics later with already borrowed: BorrowMutError, which is the runtime version of E0499.
  • Edition and NLL differences. Rust 2015 code sometimes needed explicit scopes that NLL makes unnecessary; migrating an old crate can surface borrows that now work, and cargo fix --edition handles the mechanical parts.
  • Polonius. The next-generation borrow checker relaxes some conditional-return patterns; until it lands in stable, the workaround is an explicit re-borrow after the branch.
  • Async borrows. Holding a &mut across .await in a tokio::select! branch is a frequent E0499 in async code, because the future keeps the borrow alive.

Compare a failing version of a function with a fixed one using the diff tool — borrow errors often disappear with a two-line reorder that is easy to miss in review — and use the regex tester to pull the exact borrow window out of a long cargo build log.

Primary references: E0499 documents the exact rule and its diagnostic, and References and Borrowing explains the aliasing rules the checker enforces.

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.