Sub topic 10
Reading and writing for<'a>
This chapter explains the for<'a> syntax: what it quantifies, where it can appear, and how to read it. It assumes you know basic lifetime annotations, generics with trait bounds, and the Fn traits. It also assumes you have seen why a single lifetime parameter is not enough for a callback that must accept references of any lifetime.
The problem in one example
Suppose a function wants to call a closure twice, once with a borrow of a local String and once with a 'static literal. The natural first attempt names a lifetime on the function:
// Does not compile.
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)
}A lifetime parameter on a function is chosen by the caller. It must outlive the whole call, so it also outlives every local variable inside the body. &owned cannot live that long, so the compiler rejects the call to f.
The bound needs to say something different: "f works for every lifetime, and I will pick one at each call." That is what for<'a> says.
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 first call uses a short lifetime tied to owned. The second uses 'static. Both are valid instances of the one bound.
What the syntax means
for<'a> is a universal quantifier over lifetimes. Read F: for<'a> Fn(&'a str) -> &'a str as:
> For every lifetime 'a, F implements Fn(&'a str) -> &'a str.
The word "higher-ranked" refers to this. An ordinary bound is about one fixed instantiation. A higher-ranked bound is a statement about all instantiations at once.
Two consequences follow.
- The lifetime is bound inside the bound. The name
'aexists only within thefor<'a>clause. It is not a generic parameter of the function, and you cannot use it elsewhere in the signature. Choose a name that does not clash with lifetimes already in scope. - Choice moves from the caller to the callee. With a named parameter, the caller of
apply_to_bothpicks'a. Withfor<'a>, the body ofapply_to_bothpicks'aat every call tof. The caller ofapply_to_bothmust instead supply something that works for all of them.
The table summarizes the two.
| Row | `<'a, F> ... F: Fn(&'a str) -> &'a str` | `F: for<'a> Fn(&'a str) -> &'a str` |
|---|---|---|
| Who picks `'a` | The caller of `apply_to_both` | The code that calls `f`, at each call |
| Number of lifetimes | One, fixed for the whole function | A fresh one per call |
| Can `'a` be shorter than the function body | No | Yes |
| What the argument must satisfy | One lifetime | All lifetimes |
Where for<'a> can appear
The binder attaches to a bound or a type. These forms are all valid.
- Inline in a bound:
F: for<'a> Fn(&'a str) -> &'a str - On a where predicate:
where for<'a> F: Fn(&'a str) -> &'a str - On a trait object:
Box<dyn for<'a> Fn(&'a str) -> &'a str> - On a function pointer type:
for<'a> fn(&'a str) -> &'a str
Forms 1 and 2 mean the same thing for a bound like this one. The where-clause form becomes necessary when the type on the left side itself mentions the lifetime, for example for<'a> &'a C: IntoIterator. That case is covered later in this tutorial.
The next program uses forms 3 and 4 together:
fn trim_it(s: &str) -> &str {
s.trim()
}
fn make_trimmer() -> Box<dyn for<'a> Fn(&'a str) -> &'a str> {
Box::new(trim_it)
}
fn main() {
let p: for<'a> fn(&'a str) -> &'a str = trim_it;
let t = make_trimmer();
let owned = String::from(" hi ");
println!("{:?}", t(&owned));
println!("{:?}", t(" lit "));
println!("{:?}", p(&owned));
}trim_it is an ordinary function with an elided lifetime. Its signature is already for<'a> fn(&'a str) -> &'a str, so it fits both the boxed trait object and the pointer type.
Multiple lifetimes and mixed bounds
A binder can introduce several lifetimes, separated by commas. Use this when the bound relates more than one reference:
fn call_with_two<F>(f: F) -> usize
where
F: for<'a, 'b> Fn(&'a str, &'b str) -> usize,
{
let local = String::from("local");
f(&local, "static") + f("static", &local)
}
fn main() {
println!("{}", call_with_two(|x, y| x.len() + y.len()));
}'a and 'b are independent. The bound promises that f works whether the two borrows have the same lifetime or unrelated ones.
A binder covers only the bound it is attached to. In F: for<'a> Fn(&'a str) -> &'a str, G: Clone, the name 'a is not visible in G: Clone. Each bound that needs a quantified lifetime needs its own for<...>.
Reading the output position
The return type matters as much as the arguments. Compare:
for<'a> Fn(&'a str) -> &'a str: the output borrows from the input. Whatever lifetime the caller supplies comes back out.for<'a> Fn(&'a str) -> &'static str: the output is independent of the input.for<'a> Fn(&'a str) -> String: the output owns its data and carries no lifetime at all.
When a closure's body returns a slice of its argument, only the first form describes it. A closure like |s| s.trim() satisfies the first and third kinds of bound (after conversion to String), but it does not satisfy the second, because trim returns a borrow of s.
A rule for when you need it
You need an explicit for<'a> when the lifetime must be chosen by the code that uses the value and cannot be named in the signature. Typical signs:
- The function creates the borrow itself, as with
&ownedabove. - The same callback is called with borrows of different origins.
- The bound is on a reference to a generic type, such as
&'a C, and the reference is created inside the body.
If the caller already has the reference and passes it in, a normal named parameter is usually enough. Prefer the simpler form when it works.
Exercise
A function is declared as fn run<'a, F: Fn(&'a str) -> usize>(f: F), and its body calls f(&String::from("x")). Why does this fail to compile, and what is the one-line change to the bound that fixes it?
Show answer
'a is a parameter chosen by the caller, so it must outlive the entire call to run. The temporary String created in the body is dropped earlier, so borrowing it as &'a str is an error. Remove 'a from the parameter list and change the bound to F: for<'a> Fn(&'a str) -> usize, which lets the body pick a new lifetime for each call.
Exercise
Write the type of a boxed trait object that holds a callback taking two string slices of independent lifetimes and returning the length of the first as a usize.
Show answer
Box<dyn for<'a, 'b> Fn(&'a str, &'b str) -> usize>