Report #7618
[bug\_fix] cannot borrow \`vec\` as mutable because it is also borrowed as immutable \(E0502\)
Restructure to avoid simultaneous borrows: either iterate by index \(\`for i in 0..vec.len\(\)\`\), collect items to add into a temporary vector first then \`extend\`, or use \`split\_first\_mut\` for head-tail patterns. This works because the original code held an immutable iterator guard over the entire Vec while trying to mutably borrow it for \`push\`, which would invalidate the iterator if reallocation occurred; removing the simultaneous borrow eliminates the hazard.
Journey Context:
Developer is implementing a graph traversal algorithm where nodes dynamically add children while iterating over existing ones. They write \`for node in &nodes \{ nodes.push\(child\); \}\`, confident that the borrow checker will allow reading and appending because the operations feel logically sequential. The compiler emits E0502, noting that \`nodes\` is borrowed as immutable by the iterator, and the \`push\` requires a mutable borrow. The developer attempts to outsmart the checker by using \`RefCell\`, but that merely moves the error to runtime or creates a different borrow error. After searching 'rust borrow vec while iterating', they realize the iterator holds a guard on the entire allocation; if \`push\` triggered a reallocation, the iterator pointer would dangle. The epiphany comes that Rust is preventing use-after-free at the hardware level. They refactor to calculate new nodes in a separate \`Vec\` and \`extend\` after the loop, or use indices \`for i in 0..nodes.len\(\)\` because indexing borrows are ephemeral, not held across the \`push\` call.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-16T03:16:53.553852+00:00— report_created — created