Fix a method whose returned &String keeps the &mut self borrow alive
get_or_insert takes &mut self, inserts a value when the key is missing and returns a shared &String. The caller holds that reference and calls cache.len(), which fails with E0502 (cache borrowed as immutable while also borrowed as mutable), although the returned reference only reads. Explain why, and restructure the API.
Requirements:
- Keep the insert-if-missing behaviour;
mainprintsv1 1. - No
unsafe, noRefCell, nocloneof the value.
use std::collections::HashMap;
struct Cache {
map: HashMap<u32, String>,
}
impl Cache {
fn get_or_insert(&mut self, k: u32) -> &String {
self.map.entry(k).or_insert_with(|| format!("v{k}"))
}
fn len(&self) -> usize {
self.map.len()
}
}
fn main() {
let mut cache = Cache { map: HashMap::new() };
let v = cache.get_or_insert(1);
let n = cache.len();
println!("{v} {n}");
}Find and fix the bug.
The &String returned by a &mut self method reborrows that &mut, so cache stays exclusively borrowed while v is used, and cache.len() is E0502. Split the API: a &mut self method that inserts, then a &self getter for the value.
- Assuming a shared reference returned from a
&mut selfmethod downgrades the borrow to shared - Trying to give the returned reference a lifetime unrelated to
self - Blaming
HashMap::entryinstead of the method signature
- Why can't the compiler downgrade the
&mut selfborrow to shared once the method returns? - How would returning
(&String, usize)from the method change the call site?
By the elision rules, fn get_or_insert(&mut self, k: u32) -> &String reads as fn get_or_insert<'a>(&'a mut self, k: u32) -> &'a String: the result lives as long as the &'a mut self borrow. While v is in use, the &mut cache is alive too, so cache.len() (a shared borrow) conflicts with it. The compiler may not downgrade the &mut to shared: a &mut self method may rely on exclusive access — for example, hand out a reference into a Mutex's data without locking, as Mutex::get_mut does — and access through &self next to that reference would then be unsound. The check relies only on the signature, not on the method body.
The fix separates mutation from reading:
use std::collections::HashMap;
struct Cache {
map: HashMap<u32, String>,
}
impl Cache {
fn ensure(&mut self, k: u32) {
self.map.entry(k).or_insert_with(|| format!("v{k}"));
}
fn get(&self, k: u32) -> Option<&String> {
self.map.get(&k)
}
fn len(&self) -> usize {
self.map.len()
}
}
fn main() {
let mut cache = Cache { map: HashMap::new() };
cache.ensure(1); // the &mut borrow ends here
let v = cache.get(1).expect("inserted above");
let n = cache.len(); // two shared borrows coexist
println!("{v} {n}"); // v1 1
}When the API cannot change, reordering the call site works: let n = cache.len(); first, then get_or_insert. Another option returns everything needed in one call, such as (&String, usize). A separate lifetime 'a unrelated to self does not compile: lifetime may not live long enough.