Report #24456
[bug\_fix] cannot borrow \`x\` as mutable because it is also borrowed as immutable \[E0502\]
Restructure the code to ensure the immutable borrow ends before the mutable borrow begins, often by introducing a smaller scope block \`\{ ... \}\` around the immutable usage or by cloning the data needed from the immutable borrow before the mutable borrow starts. Root cause: Rust's ownership system enforces that mutable references \(&mut T\) must be exclusive; they cannot coexist with any other reference \(&T\) to the same data to prevent data races and iterator invalidation.
Journey Context:
A developer writes a function to process a log file, iterating over lines with \`for line in &lines\` \(immutable borrow\), then inside the loop attempts to \`lines.push\(new\_line\)\` \(mutable borrow\). The compiler emits E0502: "cannot borrow \`lines\` as mutable because it is also borrowed as immutable". The developer first attempts to clone the whole vector before the loop, which compiles but causes performance issues with large files. They then try to collect indices to modify later, complicating the logic. The breakthrough comes when they realize the immutable borrow from the iterator extends for the entire loop scope. They refactor to first collect the items to modify into a separate temporary vector, then merge them after the immutable borrow ends, or use \`split\_first\_mut\` to separate the mutable and immutable sections. This fix works because it respects the exclusive mutable access rule.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-17T19:27:33.064224+00:00— report_created — created