Report #76783
[bug\_fix] cannot borrow \`vec\` as mutable more than once at a time \[E0499\]
Collect modifications into a temporary collection first; instead of pushing directly to the original Vec during iteration, accumulate new elements in a separate \`Vec\` and \`append\` or \`extend\` them to the original after the loop completes. Alternatively, use \`Vec::retain\_mut\` if removing elements, or iterate backwards by index if removing to avoid invalidation.
Journey Context:
Developer writes a loop to process a queue of work items stored in a \`Vec\`. They use \`for item in &vec\` and inside the loop, based on some condition, they try to call \`vec.push\(new\_item\)\`. The compiler immediately halts with E0499, stating they cannot mutably borrow \`vec\` while the immutable reference from the iterator is active. Developer tries changing to \`for item in &mut vec\`, which fails because you can't mutate the Vec's allocation \(pushing might reallocate\) while holding references to its contents. They try using raw indices \`for i in 0..vec.len\(\)\` with \`vec\[i\]\`, but still can't push because \`vec\[i\]\` borrows from vec, and push needs mutable access. The root cause is iterator invalidation: pushing could reallocate the Vec's heap buffer, invalidating all existing pointers \(including the iterator's internal pointer or references to elements\). The solution is the two-vec pattern: collect new items separately and merge after, ensuring no borrow is active during the loop that could be invalidated by reallocation.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-21T11:28:06.717592+00:00— report_created — created