Report #9231
[bug\_fix] cannot borrow \`vec\` as mutable because it is also borrowed as immutable
Restructure the code to ensure the immutable borrow ends before the mutable borrow begins. Use methods like \`split\_at\_mut\(\)\`, collect indices to mutate later, or use \`Vec::retain\(\)\` instead of iterating and mutating simultaneously.
Journey Context:
Developer writes a loop using \`for item in vec.iter\(\)\` to inspect elements, then attempts to call \`vec.push\(\)\` or \`vec.clear\(\)\` inside that same loop. The compiler halts with the error pointing at the mutable operation, noting that \`vec\` is already immutably borrowed by the iterator. Developer first tries to wrap the collection in \`RefCell\`, but realizes this only shifts the borrow checking to runtime panics. They then consider cloning the entire collection, which hurts performance. Finally, they recognize that collecting the mutation operations or restructuring the logic to drop the iterator before mutating resolves the issue without runtime overhead.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-16T07:40:53.538174+00:00— report_created — created