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
85%Fix Rate
88%Confidence
50Evidence
2023-01-01First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 1 | active | — | — | — |
Root Cause
Rust's borrow checker prevents simultaneous mutable and immutable borrows.
genericWorkarounds
-
90% success Restructure code to separate mutable and immutable borrow scopes
{ let r = &x; use(r); } // immutable borrow ends x.mutate(); // mutable borrow startsSources: https://doc.rust-lang.org/book/ch04-02-references-and-borrowing.html
-
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:
-
Use unsafe to bypass borrow checker
90% fail
Introduces undefined behavior, defeats Rust's safety guarantees
-
Clone everything to avoid borrows
55% fail
Unnecessary allocations, may not fix the design issue
Error Chain
Frequently confused with: