E0502 🦀 Rust

Rust: error[E0502]: cannot borrow `x` as mutable because it is also borrowed as immutable

You tried to mutate a value while an immutable reference to it is still in use.

Seen on: Rust

Meaning

Rust allows many readers or one writer at a time. Holding a reference into a Vec (e.g. from .first() or an index) and then pushing to it is the most common case.

Common causes

  • Holding a reference (iterator, slice, &v[0]) while mutating
  • Calling a &mut self method while a borrow is alive
  • Long-lived borrows in loops

⚡ Quick fix

  1. Finish using the immutable reference before mutating
  2. Copy/clone the needed value out first
  3. Collect changes and apply them after the loop

Detailed fix by platform

Rust

  1. rust
    let first = v[0];          // copy the value (i32 is Copy)
    v.push(4);
    println!("{first}");

How to diagnose

  1. Borrows — Where is the immutable borrow used later?
  2. Loop — Mutating what you iterate?

🔧 Still not fixed?

Many errors look alike. If the steps above didn’t solve it, one of these is probably what you’re facing:

🧠 Still stuck? Analyze your error

Paste the full message, response headers or stack trace — we'll detect the platform and point to the most likely cause.