Borrow-Checker Error Scenarios
Learn to read borrow-checker errors: they cite conflicting borrows and suggest fixes. Most resolve by shortening borrow scope, cloning at boundaries, or restructuring ownership.
Search across all documentation pages
Learn to read borrow-checker errors: they cite conflicting borrows and suggest fixes. Most resolve by shortening borrow scope, cloning at boundaries, or restructuring ownership.
error[E0502]: cannot borrow `x` as mutable because it is also borrowed as immutable
Fix pattern: end immutable borrow before mutable borrow (narrow scope, clone, or restructure).
Problem: holding reference while mutating container.
// Before (error)
let r = &vec[0];
vec.push(1); // invalidates r
println!("{r}");
// After
let first = vec[0];
vec.push(1);
println!("{first}");Split borrows:
let (left, right) = slice.split_at_mut(mid);
// use left and right separatelyWhat this demonstrates:
Vec::push)split_at_mut for two mutable regionsCommon errors: E0502 (borrow conflict), E0499 (two mut borrows), E0597 (does not live long enough). rust-analyzer often shows graph of borrows.
&T.borrow_mut scope.&mut self across await. Fix: owned data in task.| Alternative | Use When | Don't Use When |
|---|---|---|
Arc<Mutex<T>> | shared mutation | single-thread hot path |
| Index not reference | vec[i] copy | large non-Copy item |
| Arena indices | graph aliasing | simple tree |
Second note shows where other borrow started.
Restructure after fixing correctness first.
Future borrow checker may accept more; still write clear ownership.
Small exercises; compiler as teacher.
rust-analyzer inlay hints and fix suggestions.
State clone Arc; don't hold & across await from handler self.
Split scopes; cannot hold get while inserting same map.
Move closure or clone before move.
Lifetime parameters required; see lifetime scenarios.
Last resort; document invariants.
Stack versions: This page was written for Rust 1.97.0 (edition 2024), Tokio 1.x, Axum 0.8, serde 1.0, sqlx 0.8, clap 4, and Polars 0.46+.
Reviewed by Chris St. John·Last updated Jul 16, 2026