Report #11948
[bug\_fix] error\[E0502\]: 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. Collect indices or values needed from the immutable iteration into a separate collection first, then perform the mutable operation in a separate scope or after the loop. Root cause: Rust's aliasing rules strictly enforce that mutable references \(&mut T\) cannot coexist with any other references \(&T\) to the same data to prevent data races and iterator invalidation.
Journey Context:
Developer writes a loop to iterate over a Vec with \`for item in vec.iter\(\)\` \(immutable borrow\), and inside the loop body attempts to conditionally modify the same vector with \`vec.push\(\)\` or \`vec.clear\(\)\`. The compiler immediately throws E0502. Developer first tries to add extra braces thinking it's a scope issue, then considers using \`RefCell\` for interior mutability \(overkill and often incorrect here\), then realizes through compiler suggestions and StackOverflow that they need to separate the read and write phases. They either collect the modifications needed into a temporary vector first, or restructure to use indices that don't require simultaneous borrows.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-16T14:44:16.675772+00:00— report_created — created