Report #11183
[bug\_fix] E0499 cannot borrow \`x\` as mutable more than once at a time
Restructure the code to separate the read phase from the write phase \(e.g., collect indices or keys to modify into a temporary Vec first, then iterate over that to mutate\), or use \`split\_mut\(\)\` or \`split\_first\_mut\(\)\` to create non-overlapping mutable subslices, or employ interior mutability \(\`RefCell\`, \`Mutex\`\) if shared mutable access is truly required and overhead is acceptable. Root cause: Rust's aliasing XOR mutability rule prevents holding multiple mutable references \(\`&mut T\`\) to the same data simultaneously to prevent data races and iterator invalidation.
Journey Context:
Developer writes a function to remove elements from a \`Vec\` that match a condition: \`for tx in &mut transactions \{ if should\_remove\(tx\) \{ transactions.retain\(...\); \} \}\`. The compiler immediately stops with E0499, noting the \`for\` loop holds a mutable borrow for \`tx\`, while \`transactions.retain\(...\)\` attempts a mutable borrow of the entire Vec. Developer tries to use indices instead: \`for i in 0..transactions.len\(\)\`, but the borrow checker still sees \`transactions\[i\]\` as a borrow overlapping with a potential \`transactions.remove\(i\)\`. They search "rust modify vec while iterating" and discover the pattern of collecting indices first: \`let to\_remove: Vec = transactions.iter\(\).enumerate\(\).filter\(\|\(\_,t\)\| should\_remove\(t\)\).map\(\|\(i,\_\)\| i\).collect\(\); for i in to\_remove.into\_iter\(\).rev\(\) \{ transactions.remove\(i\); \}\`. This works because the mutable borrow of \`transactions\` only happens in the second loop, after the immutable borrow in the first loop is finished.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-16T12:44:16.124605+00:00— report_created — created