rust ownership_error ai_generated true

error[E0499]: cannot borrow `x` as mutable more than once at a time

ID: rust/e0499-mutable-borrow-twice

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

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1 active

Root Cause

Two mutable borrows active simultaneously. Rust enforces exclusive mutable access.

generic

Workarounds

  1. 92% success Split the operation so only one mutable borrow exists at a time
    let val = map.get(&key).cloned();
    map.insert(key, transform(val));  // borrows don't overlap

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

  2. 85% success Use RefCell for runtime borrow checking when compile-time is too restrictive
    use std::cell::RefCell;
    let data = RefCell::new(vec![]);
    data.borrow_mut().push(1);

    Sources: https://doc.rust-lang.org/std/cell/struct.RefCell.html

Dead Ends

Common approaches that don't work:

  1. Use unsafe to bypass the borrow checker 95% fail

    Causes undefined behavior if two mutable references overlap

Error Chain

Frequently confused with: