Report #69679
[bug\_fix] cannot borrow as mutable more than once at a time
Restructure the code to avoid simultaneous mutable borrows, typically by collecting the modifications to apply later, using \`split\_mut\` to create disjoint mutable slices, using \`retain\` or \`drain\` methods, or iterating over indices instead of references. The root cause is Rust's borrow checker enforcing that only one mutable reference \(&mut T\) can exist at a time to prevent iterator invalidation—if you modify a Vec \(e.g., pushing\) while iterating, the internal buffer might reallocate, invalidating the iterator's pointers.
Journey Context:
You're processing a Vec of items, trying to update each element based on some condition while simultaneously pushing new elements to the same vector. You write: \`for item in &mut items \{ if item.active \{ items.push\(item.child.clone\(\)\); \} \}\`. The compiler slams you with 'cannot borrow items as mutable more than once at a time'. You think 'but I'm mutating different things\!' You try to use raw pointers or unsafe blocks out of frustration. You read the error explanation and realize that \`&mut items\` from the iterator holds a borrow for the entire loop, while \`items.push\(\)\` tries to get a new mutable borrow. The 'aha' moment comes when you understand that Vec might reallocate its buffer on push, which would invalidate the iterator's pointer to the elements. You refactor to collect new items first: \`let to\_add: Vec<\_> = items.iter\(\).filter\(\|i\| i.active\).map\(\|i\| i.child.clone\(\)\).collect\(\); items.extend\(to\_add\);\`. Alternatively, you use indices: \`for i in 0..items.len\(\) \{ ... \}\` \(though this has complexity issues\). The fix works because it respects the exclusivity of mutable borrows, ensuring memory safety by preventing iterator invalidation.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-20T23:26:37.875175+00:00— report_created — created