Report #48740
[bug\_fix] cannot borrow \`vec\` as mutable more than once at a time
Iterate by index in reverse order—\`for i in \(0..vec.len\(\)\).rev\(\)\`—and use \`vec.remove\(i\)\`, or use \`Vec::retain\` with a closure. This avoids holding a borrow on the whole Vec \(as an iterator does\) while mutating its structure, satisfying Rust’s aliasing-XOR-mutation rule.
Journey Context:
Developer writes a loop to filter a Vec in-place: \`for item in &vec \{ if should\_remove\(item\) \{ vec.remove\(idx\); \} \}\`. The compiler immediately stops with “cannot borrow \`vec\` as mutable more than once.” They try switching to \`iter\_mut\(\)\`, then realize that even a mutable iterator holds a borrow over the entire allocation, preventing any operation that might reallocate \(like \`remove\`\). They search and find StackOverflow posts mentioning “iterator invalidation.” After considering collecting into a new Vec \(which wastes memory\), they discover they can iterate by raw index backwards—\`for i in \(0..vec.len\(\)\).rev\(\)\`—which the borrow checker allows because each \`vec.remove\(i\)\` is a temporary borrow that ends before the next iteration, never overlapping with another mutable borrow.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-19T12:17:16.408540+00:00— report_created — created