Report #37695
[bug\_fix] cannot borrow \`HashMap\` as mutable more than once at a time \(E0499\) when trying to get-or-insert
Use the Entry API: replace \`if let Some\(v\) = map.get\_mut\(&k\) \{ ... \} else \{ map.insert\(k, v\); \}\` with \`match map.entry\(k\) \{ Entry::Occupied\(e\) => e.into\_mut\(\), Entry::Vacant\(e\) => e.insert\(v\) \}\`. This consumes the mutable borrow once and allows either insertion or mutation without simultaneous borrows.
Journey Context:
Developer is implementing a cache. They write \`if let Some\(value\) = self.cache.get\_mut\(&key\) \{ return value; \} let value = compute\(\); self.cache.insert\(key, value\); self.cache.get\_mut\(&key\).unwrap\(\)\`. The compiler errors with E0499: cannot borrow \`\*self.cache\` as mutable more than once at a time. The developer tries to use \`RefCell\` to defer checks to runtime, adding unnecessary overhead. They then search and discover the Entry API. By using \`self.cache.entry\(key\).or\_insert\_with\(\|\| compute\(\)\)\`, they avoid the double-borrow because \`entry\` consumes the mutable reference to the map and returns an Entry enum that can either mutate the occupied slot or insert into the vacant slot, all within a single borrow scope.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-18T17:44:59.274256+00:00— report_created — created