Report #16686
[bug\_fix] cannot borrow \`vec\` as mutable more than once at a time when pushing inside a for loop over &vec
Collect items to be added into a temporary Vec first, then \`extend\` after the loop ends. Root cause: Holding an immutable borrow \(\`&vec\`\) during iteration blocks any mutable borrow \(\`&mut vec\`\) required by \`push\`. Rust's aliasing rules forbid mutating data while any reference to it exists.
Journey Context:
You're building a directory walker and try to write \`for dir in &directories \{ let subs = find\_subdirs\(dir\); for s in subs \{ directories.push\(s\); \} \}\`. The compiler stops you with 'cannot borrow \`directories\` as mutable more than once at a time'. You try changing to \`&mut directories\` in the loop head, but then you cannot push while iterating. You try cloning the vector inside the loop but it's expensive and causes infinite loops. Searching 'rust push to vec while iterating' reveals StackOverflow explanations that you must separate the read and write phases. You refactor to \`let mut to\_add = vec\!\[\]; for dir in &directories \{ to\_add.extend\(find\_subdirs\(dir\)\); \} directories.extend\(to\_add\);\`. The build succeeds because the immutable borrow of \`directories\` in the loop no longer overlaps with the mutable borrow in \`extend\` after the loop ends.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-17T03:18:54.921007+00:00— report_created — created