Why does stable rustc reject a Rust cache method that returns the hit from `self.cache.get(&id)` early and inserts on a miss, and how do you fix it?
answer
- a returned borrow outlives the call
- the miss path is not exempt
- a known NLL limitation
- entry API, or check first
basics
~20 sReturning hit makes the shared borrow from get last for the caller's lifetime, and stable rustc's borrow checker extends that borrow over the miss path too, where insert needs &mut. It reports E0502; the entry API or a contains_key check fixes it.
solid answer
~50 sIn `fn label(&mut self, id: u32) -> &String`, returning `hit` requires the borrow created by `self.cache.get(&id)` to live as long as the returned reference, the lifetime of `&mut self`. The current borrow checker gives that borrow one region, and because the region must reach the end of the function on the return path, it also covers the `insert` on the path where nothing was returned. So stable rustc 1.99 reports E0502, labelling "returning this value requires that `self.cache` is borrowed for `'1`"; with `get_mut` it is E0499. The code is sound, and the Rustonomicon lists the pattern as a known limitation. Fixes that compile today: `self.cache.entry(id).or_insert_with(..)`, one lookup under one `&mut` borrow; or test `contains_key`, insert on a miss, then index, so no borrow escapes from inside the `if`. Polonius, a borrow checker that accepts the original, is only behind the unstable `-Z polonius` flag.
code
rust · 20 linesuse std::collections::HashMap;
struct Layout {
cache: HashMap<u32, String>,
}
impl Layout {
fn label(&mut self, id: u32) -> &String {
if let Some(hit) = self.cache.get(&id) {
return hit;
}
self.cache.insert(id, format!("node-{id}"));
&self.cache[&id]
}
}
fn main() {
let mut l = Layout { cache: HashMap::new() };
println!("{}", l.label(3));
}go deeper
Recall that returning a reference from a method keeps the field borrowed for as long as the caller uses it, and that HashMap's entry API is the standard get-or-insert.
Explain why the early return makes the borrow outlive the function and why the miss path is still treated as borrowed.
Name this as a known limitation of the current borrow checker, rewrite it with entry, a check-then-borrow or an owned result, and refuse unsafe or RefCell workarounds in review.
Weigh API shape: returning keys, owned values or entry-style handles from caches avoids this class of error for every caller, not just inside one method.
## The pattern A layout cache in a graph editor maps node ids to labels. The natural method looks up the id, returns the cached label on a hit, and computes and inserts it on a miss: - `if let Some(hit) = self.cache.get(&id) { return hit; }` - `self.cache.insert(id, format!("node-{id}"));` - `&self.cache[&id]` On every real execution the shared borrow from `get` is either returned, and the function ends, or it is dead, and the `insert` runs with no live borrow. The program is sound. Stable rustc 1.99 rejects it anyway. ## What rustc reports - **E0502**, "cannot borrow `self.cache` as mutable because it is also borrowed as immutable" - "let's call the lifetime of this reference `'1`" under `&mut self` - "returning this value requires that `self.cache` is borrowed for `'1`" under `hit` - `mutable borrow occurs here` under the `insert` The same function written with `match self.cache.get_mut(&id) { Some(hit) => hit, None => { .. } }` and a `&mut String` return is E0499, two mutable borrows. The Rustonomicon shows that exact shape in its section on improperly reduced borrows, with the E0499 output. ## Why non-lexical lifetimes are not enough Non-lexical lifetimes compute a **region** for each borrow: the set of program points where it must be valid. Returning `hit` adds a constraint that the borrow's region outlive `'1`, the lifetime the caller chose for `&mut self`, which extends past the end of the function. The current checker does not record that this constraint arises only on the path that returned. It applies it to the borrow everywhere the borrow could flow, so the region includes every point from the `get` call to the function exit, the `insert` on the miss path among them. Under that region the `insert` conflicts with a borrow that is, in reality, dead. This is the best-known case NLL does not accept. A related one in the same Rustonomicon chapter is **downgrading**: a method `fn add(&mut self, n: u32) -> &u32` returns a shared reference, but the caller's `&mut` borrow of the receiver stays active as long as that result is used, so a following `g.len()` call is E0502 while the result is still alive. ## Fixes that compile on stable 1. **The entry API.** `self.cache.entry(id).or_insert_with(|| format!("node-{id}"))` performs lookup-or-insert under one `&mut` borrow and returns `&mut String`, which coerces to `&String`. One hash lookup, no conflict. 2. **Check, then borrow.** `if !self.cache.contains_key(&id) { self.cache.insert(..); }` followed by `&self.cache[&id]`. No borrow is returned from inside a branch, so the regions never overlap. The cost is a second lookup on a hit. 3. **Return an owned or `Copy` result.** If callers only need a length or a cloned label, returning `usize` or `String` removes the escaping borrow; the original shape compiles as soon as the early return no longer carries a reference. 4. **Return a key or index.** Return the `u32` id, and let the caller index the cache when it needs the label. | Rewrite | Key hashes on a hit | Key hashes on a miss | Returns a borrow | |---|---|---|---| | `entry(id).or_insert_with(..)` | 1 | 1 | yes | | `contains_key`, `insert`, index | 2 | 3 | yes | | owned or `Copy` result | 1 | 3 | no | The entry API is the default choice; the others are for when the API shape itself should change. ## What not to do - Do not reach for `unsafe` to extend the borrow; the pattern has safe rewrites and the soundness argument is easy to get wrong. - Do not put the cache behind `RefCell` just to silence this error; that trades a compile-time error you can restructure around for a runtime panic. - Do not assume your toolchain will accept it soon: as of rustc 1.99 the Polonius borrow checker exists only behind the unstable compiler flag `-Z polonius`, documented as "default: no". ## How to recognise it in review The signature returns a reference tied to `&mut self` or a `&mut` parameter; one branch returns a borrow obtained from a field; another branch mutates that same field. When those three hold and the error says "returning this value requires that ... is borrowed for `'1`", you are looking at this limitation, not at a real aliasing bug.
- Why does the same function compile if it returns `hit.len()` instead of `hit`?Returning a `usize` does not tie the borrow from `get` to `'1`. The borrow is then dead after `hit.len()` is computed, non-lexical lifetimes end it there, and the `insert` on the miss path has no live borrow to conflict with.
- Why is the entry API usually better than the `contains_key` rewrite?`entry` hashes the key once, searches once, and keeps a single `&mut` borrow from lookup to insertion, so it is both borrow-checker-friendly and one hash on every path. The `contains_key` version hashes the key again on a hit, which matters on hot paths.
- What is the downgrading case, and how do you work around it?A method like `fn add(&mut self, n: u32) -> &u32` returns a shared reference, but the receiver stays mutably borrowed while that result is used, so a later `g.len()` is E0502. Call `g.len()` before `add`, or copy the result out with `let added = *g.add(5);`, so the reference is not kept alive.
- Non-lexical lifetimes accept every borrow pattern that is actually sound.
- The error means the code would really alias the cache at run time.
- The fix is to wrap the cache in RefCell.
- Polonius is the default borrow checker in current stable Rust.
- The entry API hashes the key twice, just like contains_key plus insert.
Assumes stable rustc 1.99 on edition 2024, which still rejects this pattern; the Polonius borrow checker that accepts it is available only behind the unstable -Z polonius flag.