Sub topic 15
Diagnosing variance and HRTB errors
This chapter assumes you know ownership and borrowing, basic lifetime annotations, generics with trait bounds, and the Fn, FnMut and FnOnce traits. It also builds on the earlier chapters on variance and for<'a>. Here you will learn to read the errors those features produce, work out the cause, and choose a fix.
Two families of errors
Most advanced lifetime errors fall into one of two groups.
- Variance errors. A lifetime was meant to shrink, but the type is invariant in it, so it could not. The compiler reports this as a plain borrow error ("does not live long enough"). It never mentions the word variance.
- Higher-ranked errors. A bound needs a callable or trait implementation that works for every lifetime, but what you supplied works for only one. The compiler reports this as "implementation of
Fnis not general enough" or as a lifetime-mismatch message.
The first step is to decide which family you are in.
Variance errors
Symptom: a borrow that "should" shrink does not
Here is the failing example from the variance chapters again.
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}");
}Read the error from the end. The compiler says local is borrowed for 'static. You never wrote 'static on that borrow. It came from the annotation on s.
shas type&'static str.&mut shas type&mut &'static str, and&mut Tis invariant inT.- The parameter
slot: &mut &'a strtherefore forces'a = 'staticexactly. value: &'a stris then also&'static str, and&localcannot satisfy that.
The rejection is correct. If 'a could shrink, assign could store a short-lived reference into a variable that claims to hold 'static data.
The fix is to stop claiming more than is true. Remove the 'static annotation so that s gets an ordinary inferred lifetime:
fn assign<'a>(slot: &mut &'a str, value: &'a str) {
*slot = value;
}
fn main() {
let mut s: &str = "hello";
let local = String::from("temp");
assign(&mut s, &local);
println!("{s}");
}Now 'a is the region from the assignment to the last use of s. The literal "hello" is 'static and coerces to that shorter lifetime when it initializes s, because the shared reference is covariant. The invariance only applies behind the &mut.
Symptom: a struct that looks fine becomes unusable after a borrow
Interior mutability makes a struct invariant in its lifetime. The error then shows up far from the struct definition.
use std::cell::RefCell;
struct Registry<'a> {
names: RefCell<Vec<&'a str>>,
}
fn fill<'a>(r: &Registry<'a>, s: &'a str) {
r.names.borrow_mut().push(s);
}
fn main() {
let r = Registry { names: RefCell::new(Vec::new()) };
{
let local = String::from("x");
fill(&r, &local); // error: `local` does not live long enough
}
println!("{}", r.names.borrow().len());
}RefCell<T> is invariant in T, so Registry<'a> is invariant in 'a. The 'a inside r cannot shrink to fit local. It must be at least as long as r is used, and r is used after local is gone.
The fix is usually to reorder declarations so the borrowed value outlives the container:
use std::cell::RefCell;
struct Registry<'a> {
names: RefCell<Vec<&'a str>>,
}
fn fill<'a>(r: &Registry<'a>, s: &'a str) {
r.names.borrow_mut().push(s);
}
fn main() {
let local = String::from("x");
let r = Registry { names: RefCell::new(Vec::new()) };
fill(&r, &local);
println!("{}", r.names.borrow().len());
}Locals drop in reverse order, so r is dropped before local.
If reordering is impossible, the container is the wrong design. Store owned String values, or restructure so the registry does not hold borrows tied to a shorter scope.
Splitting one lifetime into two
Sometimes the signature over-constrains. A function that ties two unrelated references to one 'a can make an invariant position force them to be equal. Give each reference its own lifetime and add an outlives bound only where the body needs it:
fn assign<'long, 'short>(slot: &mut &'short str, value: &'long str)
where
'long: 'short,
{
*slot = value;
}
fn main() {
let mut s: &str = "hello";
let local = String::from("temp");
assign(&mut s, &local);
println!("{s}");
}This is also valid, and it states the real relationship: the stored value must outlive what the slot promises.
Higher-ranked errors
Symptom: "implementation of `Fn` is not general enough"
The message means the bound requires for<'a> Fn(&'a str), which is a function that accepts any lifetime, but the value you supplied accepts only one specific lifetime.
fn only_static(s: &'static str) -> usize {
s.len()
}
fn call_with_local<F>(f: F) -> usize
where
F: Fn(&str) -> usize,
{
let owned = String::from("local");
f(&owned)
}
fn main() {
call_with_local(only_static); // error: implementation of `Fn` is not general enough
}Fn(&str) -> usize elides to for<'a> Fn(&'a str) -> usize. The function only_static has type fn(&'static str) -> usize. It cannot accept the borrow of owned, so it is not a valid argument. Direction matters here: a higher-ranked function can be used where a 'static-only one is expected, but not the other way around.
Pick one of two fixes:
- Loosen the function: change the parameter to
&str. - Tighten the bound, only if every call really uses
'staticdata: writeF: Fn(&'static str) -> usizeand callf("literal").
Symptom: a closure stored in a variable is rejected
Closure signatures are inferred, and the inference needs a hint. When a closure is passed directly to a function with an Fn(&T) bound, the compiler reads the expected signature from the bound. When you first bind the closure to a variable, there is no expected signature, and the compiler picks one concrete lifetime for the parameter.
fn apply<F>(f: F) -> usize
where
F: for<'a> Fn(&'a str) -> &'a str,
{
let owned = String::from(" hi ");
f(&owned).len() + f("lit").len()
}
fn main() {
let f = |s| s;
println!("{}", apply(f)); // error: implementation of `Fn` is not general enough
}The exact wording of the message differs between compiler versions. Some say "lifetime may not live long enough" instead. Either way, the cause is the same.
The idiomatic fix is an identity helper whose only job is to supply the expected signature:
fn apply<F>(f: F) -> usize
where
F: for<'a> Fn(&'a str) -> &'a str,
{
let owned = String::from(" hi ");
f(&owned).len() + f("lit").len()
}
fn constrain<F>(f: F) -> F
where
F: for<'a> Fn(&'a str) -> &'a str,
{
f
}
fn main() {
let f = constrain(|s| s);
println!("{}", apply(f));
}Passing the closure inline to apply also works, if you do not need the variable.
Symptom: a missing lifetime name in a where clause
On a non-Fn trait, elision does not apply. A bound such as where &C: IntoIterator<Item = &i32> is rejected because the compiler needs an explicit name for the lifetime. Write the binder yourself:
fn sum_all<C>(c: &C) -> i32
where
for<'a> &'a C: IntoIterator<Item = &'a i32>,
{
c.into_iter().sum()
}
fn main() {
let v = vec![1, 2, 3];
println!("{}", sum_all(&v));
}Quick reference
| Symptom | Likely cause | First fix to try |
|---|---|---|
| `does not live long enough`, borrow looks short enough | A `&mut` or `Cell`/`RefCell` made a lifetime invariant | Remove an over-strict annotation such as `'static` on a variable, or reorder declarations |
| Error appears after adding interior mutability to a struct | The struct became invariant in its lifetime | Declare the borrowed data before the container |
| `implementation of Fn is not general enough` with a named function | The function takes one fixed lifetime such as `&'static str` | Make its parameter `&str` |
| Same error with a closure in a `let` | No expected signature, so one lifetime was inferred | Use a `constrain` helper or pass the closure inline |
| Missing lifetime name in a `where` clause | Elision does not apply outside `Fn` sugar | Write `for<'a>` explicitly |
A working method
- Read the lifetime names in the message. If it names
'staticbut you never wrote it, search for the annotation that introduced it. - Find the invariant position: a
&mut, aCell,RefCellorMutex, or a struct containing one. - Decide whether the relationship is truly equal or merely "outlives". If it is "outlives", split the lifetimes.
- For "not general enough", write out the full
for<'a>form of the bound and of the value you pass. Compare the two signatures. - Fix the narrower side: give the function or closure the general signature.
Exercise
This code fails with "implementation of Fn is not general enough". Explain why, and give the smallest change that makes it compile.
fn run<F: Fn(&str) -> usize>(f: F) -> usize {
let s = String::from("abc");
f(&s)
}
fn count(s: &'static str) -> usize {
s.len()
}
fn main() {
println!("{}", run(count));
}
Show answer
The bound Fn(&str) -> usize is shorthand for for<'a> Fn(&'a str) -> usize, so run calls f with a borrow of the local s, which is not 'static. The function count has type fn(&'static str) -> usize, which accepts only 'static strings, so it does not implement the higher-ranked bound. The smallest fix is to change count to fn count(s: &str) -> usize. That gives it the type for<'a> fn(&'a str) -> usize, which satisfies the bound.