Report #45256
[bug\_fix] cannot borrow \`vec\` as mutable more than once at a time \(iterator invalidation\)
Collect keys or indices into a temporary Vec first, then iterate that collection to mutate the original container: \`let keys: Vec<\_> = map.keys\(\).cloned\(\).collect\(\); for k in keys \{ map.get\_mut\(&k\).unwrap\(\).push\(...\); \}\`
Journey Context:
Developer writes a loop that iterates mutably over a HashMap with \`iter\_mut\(\)\`, then inside the loop tries to insert a new key into the same map, or calls a method that borrows \`&mut self\` again. The compiler throws E0499. The developer tries to wrap the map in \`RefCell\` or \`Rc\`, which either fails to compile \(cannot borrow mutably twice even with RefCell at runtime\) or panics. The rabbit hole goes through reading about interior mutability, then realizing the actual issue is iterator invalidation: the mutable iterator holds a unique borrow for the entire loop duration, and modifying the collection would change the underlying memory layout, invalidating the iterator's pointers. The fix works because it splits the borrow: first an immutable borrow to collect the keys \(which doesn't invalidate\), then releasing that borrow before the mutable borrows in the second loop.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-19T06:25:48.588838+00:00— report_created — created