Report #17446
[bug\_fix] cannot borrow \`self\` as mutable more than once at a time when iterating over \`self.items\` and calling \`self.method\` inside the loop
Restructure to avoid simultaneous borrows: either collect the items to process first \(e.g., \`let keys: Vec<\_> = self.map.keys\(\).cloned\(\).collect\(\);\`\), then iterate over the temporary collection while calling \`self.mutate\(\)\`. Alternatively, use \`HashMap::retain\` if the logic fits, or split the struct into fields using \`split\_mut\` if applicable.
Journey Context:
Developer has a struct \`Cache\` with a field \`HashMap\`. They write a method \`purge\_expired\(&mut self\)\` that iterates over \`self.map\` and for each entry checks if expired, and if so, calls \`self.remove\(key\)\` or \`self.stats.increment\(\)\`. The compiler complains that \`self\` is borrowed mutably by the iterator, and then they try to borrow \`self\` again mutably inside the loop. They try to use \`RefCell\` or \`Mutex\` but it's overkill. They search and find patterns like 'collect the keys first': \`let keys: Vec<\_> = self.map.keys\(\).cloned\(\).collect\(\); for key in keys \{ ... \}\` or using \`retain\`. They realize that the borrow checker is protecting against iterator invalidation. The fix is to separate the iteration from the mutation by collecting keys or using \`HashMap::retain\` if the logic fits.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-17T05:22:45.207946+00:00— report_created — created