Report #10836
[bug\_fix] cannot borrow \`vec\` as mutable more than once at a time in loop \(E0499\)
Use \`Vec::retain\` to filter elements in place: \`vec.retain\(\|&x\| x % 2 == 0\);\`. Alternatively, collect indices or changes into a temporary collection first, then apply them after the iteration \(e.g., \`drain\` or \`extend\` from a new vec\). Root cause: Holding a mutable iterator \(or any mutable borrow\) to a Vec prevents any other operation that might reallocate the Vec \(like \`push\` or \`remove\`\), as that would invalidate the iterator's pointers.
Journey Context:
Developer wants to remove odd numbers from a \`Vec\`. They write \`for i in 0..vec.len\(\) \{ if vec\[i\] % 2 \!= 0 \{ vec.remove\(i\); \} \}\`. The compiler errors with E0499 about multiple mutable borrows, or warns about index shifting. Developer tries \`for item in &mut vec \{ if \*item % 2 \!= 0 \{ vec.remove\(... \} \}\` which also fails. They try using \`vec.iter\_mut\(\).filter\(\)\` but can't figure out how to mutate the original vec. They search "rust remove elements from vec while iterating". They discover \`Vec::retain\`, an in-place filtering method that safely handles the mutations internally using logic that the borrow checker can verify. They rewrite to \`vec.retain\(\|&x\| x % 2 == 0\);\` and it compiles and runs efficiently. They realize that trying to manually mutate a collection while holding any reference to it \(including an iterator\) is architecturally blocked by the borrow checker to prevent use-after-free bugs.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-16T11:46:37.692425+00:00— report_created — created