Report #13392
[bug\_fix] E0502: cannot borrow \`self\` as mutable because it is also borrowed as immutable
Restructure to end the immutable borrow before the mutable borrow begins, typically by collecting necessary data into a temporary variable first, or by refactoring the method to avoid holding both borrows simultaneously. Alternatively, use indices instead of references for the iteration.
Journey Context:
Developer is implementing a method on a struct containing a \`Vec\`. They write a loop \`for item in &self.items\` to check a condition on each item. Inside the same loop, upon finding a match, they attempt to call \`self.process\(item\)\` which takes \`&mut self\`. The compiler halts with E0502, noting that \`self\` is immutably borrowed by the iterator and the borrow lasts until the end of the loop. Developer attempts to wrap \`self\` in \`RefCell\`, leading to runtime panics. They try cloning the items, but \`Item\` lacks the \`Clone\` trait. After reviewing the borrow checker output, they realize the immutable borrow from \`&self.items\` persists for the entire loop body. The fix involves splitting the logic: first, collect the identifiers or indices of items to process into a temporary \`Vec\` \(which drops the immutable borrow once the collection is complete\), then iterate the temporary \`Vec\` and call the mutable method in a second loop.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-16T18:41:38.745432+00:00— report_created — created