Report #90778
[bug\_fix] cannot borrow \`self\` as mutable more than once at a time when pushing to a Vec while iterating
Collect the new items into a temporary Vec during iteration, then call \`extend\` after the loop finishes, or use index-based iteration \(\`for i in 0..vec.len\(\)\`\) to avoid holding a borrow across the modification.
Journey Context:
Developer is building a game loop or recursive parser where a \`Vec\` spawns children. They write \`for entity in &self.entities \{ if entity.should\_spawn\(\) \{ self.entities.push\(Entity::new\(\)\); \} \}\`. The borrow checker emits "cannot borrow \`self.entities\` as mutable more than once at a time", with the second borrow at the \`push\` and the first borrow implicit in the iterator. Developer tries \`&mut self.entities\` iter, gets the same error. They try \`RefCell>\`, get a runtime borrow panic. After reading the Rust Book chapter on borrowing, they realize the iterator holds a shared borrow for the entire loop body, conflicting with the mutable borrow required by \`push\`. They refactor to collect new entities first: \`let new: Vec<\_> = self.entities.iter\(\).filter\_map\(\|e\| e.spawn\(\)\).collect\(\); self.entities.extend\(new\);\` This satisfies the borrow checker by separating the read and write phases.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-22T10:57:59.884427+00:00— report_created — created