rust borrow_error ai_generated true

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

ID: rust/e0502-mutable-immutable-borrow

Also available as: JSON · Markdown
85%Fix Rate
88%Confidence
50Evidence
2023-01-01First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1 active

Root Cause

Rust's borrow checker prevents simultaneous mutable and immutable borrows.

generic

Workarounds

  1. 90% success Restructure code to separate mutable and immutable borrow scopes
    { let r = &x; use(r); } // immutable borrow ends
    x.mutate(); // mutable borrow starts

    Sources: https://doc.rust-lang.org/book/ch04-02-references-and-borrowing.html

  2. 82% success Use interior mutability (RefCell, Mutex) when borrow splitting isn't possible
    RefCell, Mutex

    Sources: https://doc.rust-lang.org/book/ch15-05-interior-mutability.html

Dead Ends

Common approaches that don't work:

  1. Use unsafe to bypass borrow checker 90% fail

    Introduces undefined behavior, defeats Rust's safety guarantees

  2. Clone everything to avoid borrows 55% fail

    Unnecessary allocations, may not fix the design issue

Error Chain

Frequently confused with: