Sub topic 15
Diagnosing variance and HRTB errors
This chapter assumes you know lifetime annotations, closures with Fn bounds, and the variance rules from the earlier chapters. It shows how to read the lifetime errors those features cause and how to fix them.
Start with the error's shape
Most of these errors fall into a few families. Match the message first, then look for the cause.
| Symptom | Likely cause | Typical fix |
|---|---|---|
| `implementation of Fn is not general enough` | A closure or function was inferred for one lifetime, but the bound asks for `for<'a>` | Give the closure its signature from the bound, or use a named `fn` |
| `lifetime may not live long enough` on a closure that returns a reference | The closure's return lifetime was not tied to its argument | Pass the closure straight to the function that states the bound |
| `does not live long enough` with `&mut` involved | `&mut T` is invariant in `T`, so the inner lifetime cannot shrink | Change declaration order, or split the lifetimes |
| A struct refuses to shrink its lifetime | A field such as `Cell<&'a T>` or `&mut &'a T` makes it invariant | Remove the invariant field, or accept that the lifetime is fixed |
Invariance errors
The error often points at the wrong line. Here the compiler blames local, but the cause is the type of s.
fn assign<'a>(slot: &mut &'a str, value: &'a str) {
*slot = value;
}
fn main() {
let mut s: &'static str = "hello";
let local = String::from("temp");
assign(&mut s, &local); // error: `local` does not live long enough
println!("{s}");
}Because &mut &'static str cannot shrink to &mut &'a str, 'a must be 'static. A local borrow can never satisfy that. The fix is to stop demanding 'static. Declare local first, and let s have an inferred lifetime:
fn assign<'a>(slot: &mut &'a str, value: &'a str) {
*slot = value;
}
fn main() {
let local = String::from("temp");
let mut s: &str = "hello";
assign(&mut s, &local);
println!("{s}");
}The string literal still coerces to the shorter lifetime, because &'static str is covariant when it is copied into the new variable.
"Not general enough" errors
This error means a value works for one particular lifetime, but the bound requires it to work for every lifetime. A closure only becomes higher-ranked if the compiler sees the bound while it checks the closure. If you bind the closure to a variable first, the compiler has no bound to read, so it may infer a single lifetime.
A helper that only returns its argument can force the right signature:
fn apply<F>(f: F) -> usize
where
F: for<'a> Fn(&'a str) -> &'a str,
{
let owned = String::from(" hi ");
f(&owned).len()
}
fn constrain<F>(f: F) -> F
where
F: for<'a> Fn(&'a str) -> &'a str,
{
f
}
fn main() {
// let f = |s: &str| s; // may fail: return lifetime not tied to the argument
let f = constrain(|s| s.trim());
println!("{}", apply(f));
}Passing the closure inline, as in apply(|s| s.trim()), works for the same reason. The bound is visible at the point where the closure is written.
A checklist
- Read which lifetime the message says must be longer. That names the borrow that is too short.
- Look for
&mut,Cell,RefCell, orfn(T)around the lifetime. Each can make the type invariant or contravariant. - For
Fnbounds, check whether the closure is created where the bound is visible. - If a bound mentions a borrow created inside the function body, write
for<'a>explicitly. - If a named
fnworks but a closure does not, the problem is inference, not your logic.
Exercise
A struct Holder<'a> contains a Cell<&'a str>. You pass a Holder<'static> to a function that expects Holder<'short>. Why does this fail, and which type could replace Cell to make it work?
Show answer
Cell<T> is invariant in T, so Holder<'a> is invariant in 'a and Holder<'static> cannot shrink to Holder<'short>. Replacing the field with a plain &'a str makes it covariant, so the shrink works. This is only possible if you do not need to mutate the field through a shared reference.