Sub topic 9
Why a fixed lifetime parameter is not enough
This chapter assumes you can read basic lifetime annotations, write generic functions with trait bounds, and use closures with the Fn traits. It shows one concrete failure of a named lifetime parameter and explains why the failure is unavoidable. The next chapter introduces the syntax that fixes it.
A function that takes a closure over references
Suppose you want a helper that runs a caller-supplied string transformation on two different strings and reports the lengths of the results. One string is created inside the helper. The other is a literal. The transformation takes a &str and returns a &str borrowed from its input, as str::trim does.
Lifetimes are the tool you have used so far, so you reach for a named lifetime parameter:
fn apply_to_both<'a, F>(f: F) -> (usize, usize)
where
F: Fn(&'a str) -> &'a str,
{
let owned = String::from(" owned text ");
let a = f(&owned).len(); // error: `owned` does not live long enough
let b = f(" literal ").len();
(a, b)
}This does not compile. The compiler reports that owned is dropped while it is still borrowed, and that the argument "requires that owned is borrowed for 'a".
The signature looks reasonable, so the rejection can seem arbitrary. It is not.
Who chooses the lifetime
A lifetime parameter declared on a function is chosen by the caller, in the same way a type parameter is. The function body must work for every lifetime the caller might pick. The body cannot pick a lifetime itself.
Two facts follow from this:
- Every lifetime parameter of a function outlives the function body. The caller's data already exists when the call starts, so
'acovers at least the whole call. ownedis created inside the body and dropped when the body ends. A reference to it can never last as long as'a.
The call f(&owned) requires &owned to have type &'a str. A borrow of a local variable has a lifetime limited to the body, and 'a is longer than that. The check fails.
Why covariance does not rescue you
The earlier chapters showed that a longer lifetime can stand in for a shorter one. A reference with lifetime 'long can be used where 'short is expected. That does not apply here.
The problem is the opposite direction. The local borrow is the short one, and the bound demands the long one. No subtyping rule turns a short lifetime into a long one, because that would permit dangling references.
You might ask whether the compiler can instead choose a shorter 'a for the bound. It cannot, because the caller chose 'a. The only thing the body knows about F is the bound you wrote: F works for the one lifetime 'a. The caller's closure may work for every lifetime, but the signature discards that information.
The bound also mixes two variances. Fn(&'a str) -> &'a str has 'a in an argument position (contravariant) and in the return position (covariant). The two together make 'a invariant in this bound, so the compiler has no room to adjust it.
Trying to fix it with more parameters
Adding more lifetime parameters does not help, for the same reason:
// Does not compile: still a caller-chosen lifetime.
fn apply_to_both<'a, 'b, F>(f: F) -> (usize, usize)
where
F: Fn(&'a str) -> &'a str,
{
let owned = String::from(" owned text ");
let a = f(&owned).len(); // same error
let b = f(" literal ").len();
(a, b)
}Every named parameter is supplied by the caller, and the lifetime of owned does not exist yet when the caller writes the call. There is no name you could put in the signature for "the lifetime of a variable inside this body".
What the bound should say
The intended meaning is stronger than "F works for some lifetime 'a". It is:
> For every lifetime 'a, F accepts a &'a str and returns a &'a str.
That is a universally quantified statement, and it sits inside the bound. The caller no longer picks one 'a for the whole function. The body picks a fresh 'a at each call to f, and it can use a different one each time.
Rust writes this with for<'a>:
fn apply_to_both<F>(f: F) -> (usize, usize)
where
F: for<'a> Fn(&'a str) -> &'a str,
{
let owned = String::from(" owned text ");
let a = f(&owned).len();
let b = f(" literal ").len();
(a, b)
}
fn main() {
let r = apply_to_both(|s| s.trim());
println!("{r:?}");
}This prints (10, 7). The unused <'a, ...> parameter on the function is gone. The lifetime now belongs to the bound instead of the function. The first call to f uses a lifetime that covers only &owned. The second uses 'static. Both calls are valid because F was promised to handle any lifetime.
The next chapter covers the syntax in detail. For now, keep the idea that for<'a> moves the choice of lifetime from the caller of apply_to_both to the code that calls f.
The same problem in a loop
A single local borrow is not the only trigger. Each loop iteration can create a new value with a new, shorter lifetime:
fn count_trimmed<F>(f: F) -> usize
where
F: for<'a> Fn(&'a str) -> &'a str,
{
let mut total = 0;
for i in 0..3 {
let line = format!(" line {i} ");
total += f(&line).len();
}
total
}
fn main() {
println!("{}", count_trimmed(|s| s.trim()));
}This prints 18. Each line is dropped at the end of its iteration. With a function-level 'a, all three calls would have to share one lifetime longer than the whole function. With for<'a>, each call gets its own.
Where this comes up in practice
The pattern appears whenever a generic function calls something it was given on data it owns or creates:
| Situation | Who owns the data | Lifetime parameter works? |
|---|---|---|
| Function forwards its own reference arguments to `f` | Caller | Yes |
| Function calls `f` on a local `String` or `Vec` | Function body | No, needs `for<'a>` |
| Function calls `f` on a value created in each loop iteration | Function body | No, needs `for<'a>` |
| Function calls `f` only on `'static` data | Static storage | Yes |
The first row works because the references come from the caller, so a caller-chosen 'a can describe them.
Recognizing the symptom
When a function calls a callback on its own data, the sign that you need a higher-ranked bound is an error of this shape:
- The message says a local value "does not live long enough".
- The note points at an argument that "requires that the value is borrowed for
'a", where'ais a lifetime parameter from the function signature.
If the borrowed value is a local in the body and the lifetime is declared on the function, the lifetime is in the wrong place.
Exercise
In fn run<'a, F: Fn(&'a str) -> usize>(f: F) -> usize, the body does let s = String::from("x"); f(&s). Why does this fail, and what is the one-line change to the bound that fixes it?
Show answer
The lifetime 'a is chosen by the caller and outlives the whole function body, but &s borrows a local that is dropped when the body ends, so it cannot be a &'a str. Remove 'a from the function's generics and write the bound as F: for<'a> Fn(&'a str) -> usize, so the body can pick a fresh lifetime for each call to f.
Exercise
A function takes f: F with F: for<'a> Fn(&'a str) -> &'a str and calls f on a &'static str only. Does it need for<'a>? What changes if the bound is replaced by a function-level 'a?
Show answer
It does not need for<'a> for its own body. Calling f only on 'static data works with a function-level 'a, because 'static outlives every 'a. The two bounds differ for callers. for<'a> requires a closure that works for every lifetime, while a function-level 'a asks for less. A function-level 'a therefore accepts a wider range of closures. The for<'a> form is the right choice only when the body really calls f with lifetimes it creates itself.