Sub topic 14
Higher-ranked trait bounds with for<'a>
This chapter covers the for<'a> syntax, the reason it exists, and the places you will meet it. It assumes you can already write functions with explicit lifetime parameters like fn longest<'a>(...). It also assumes you know the elision rules, and that you are comfortable with generic bounds such as F: Fn(i32) -> i32.
The problem: a callback that accepts any reference
Suppose you write a function that takes a closure and calls it with a reference that the function creates itself. The caller cannot name that reference's lifetime, because the reference does not exist yet when the caller writes the call.
The usual generic syntax for a lifetime is fn apply<'a, F>. That syntax makes the caller choose 'a. It is the wrong tool here. What you need to say is: "F must work for every possible lifetime, not one particular lifetime."
That is what a higher-ranked trait bound (HRTB) says.
fn apply<F>(f: F) -> usize
where
F: for<'a> Fn(&'a str) -> &'a str,
{
f(" hello ").len()
}
fn main() {
println!("{}", apply(|s| s.trim()));
}Read for<'a> Fn(&'a str) -> &'a str as "for all lifetimes 'a, F implements Fn(&'a str) -> &'a str." The for<'a> part introduces 'a at the bound, not on the function. Inside apply, the compiler can pick a fresh 'a for each call to f.
What goes wrong with an ordinary lifetime parameter
Compare the version where 'a belongs to the function:
fn apply_fixed<'a, F>(f: F) -> usize
where
F: Fn(&'a str) -> &'a str,
{
let local = String::from(" hello ");
f(&local).len()
// error[E0597]: `local` does not live long enough
}The caller of apply_fixed picks 'a. Whatever it picks must outlive the whole function body, because lifetime parameters of a function are valid for the entire call. The local String lives for a shorter time than that, so &local cannot be passed as &'a str. The compiler rejects it.
The for<'a> form removes the problem because 'a is no longer fixed in advance. Each call to f gets its own 'a, which can be as short as the local borrow.
You already write HRTBs without the syntax
The for<'a> syntax is rarely typed by hand, because elision inserts it for you. In the Fn family of sugar, the elision rules apply to the parenthesized argument list and the return type. These two bounds mean the same thing:
fn apply_sugar<F>(f: F) -> usize
where
F: Fn(&str) -> &str,
{
f(" hello ").len()
}Each elided lifetime in Fn(&str) -> &str becomes a higher-ranked lifetime. With one input lifetime, the output gets the same one, so the bound expands to for<'a> Fn(&'a str) -> &'a str. This is the reason that fn(&str) -> &str works as a type without any visible lifetime. A function pointer type like that is higher-ranked too.
| You write | The compiler reads |
|---|---|
| `F: Fn(&str) -> &str` | `F: for<'a> Fn(&'a str) -> &'a str` |
| `F: Fn(&str, &str) -> usize` | `F: for<'a, 'b> Fn(&'a str, &'b str) -> usize` |
| `F: Fn(&'a str) -> &'a str` (with `'a` on the function) | One lifetime, chosen by the caller |
| `F: for<'a> Fn(&'a str) -> &'a str` | Same as the first row, written out |
Reach for explicit for<'a> when the sugar cannot express what you mean. That happens in two main situations, covered next.
When you must write for<'a>
Bounds on references to a generic type
Sugar only exists for Fn, FnMut, and FnOnce argument lists. A bound on &T for a generic T has no such sugar. Here the function wants to add references to values of type T, without taking ownership of them:
use std::ops::Add;
fn sum_refs<T>(items: &[T]) -> T
where
T: Default,
for<'a> &'a T: Add<&'a T, Output = T>,
{
let mut acc = T::default();
for item in items {
acc = &acc + item;
}
acc
}
fn main() {
println!("{}", sum_refs(&[1i32, 2, 3]));
println!("{}", sum_refs(&[0.5f64, 1.5]));
}The expression &acc + item borrows acc for a short, local lifetime. The loop creates a new borrow on each iteration. The bound for<'a> &'a T: Add<&'a T, Output = T> promises that addition works for every lifetime, so each of those borrows is allowed.
If you wrote &'a T: Add<&'a T, Output = T> with 'a on the function, the compiler would demand that acc be borrowed for the whole call. That conflicts with reassigning acc.
Boxed trait objects holding callbacks
Box<dyn Fn(&str) -> &str> also gets the higher-ranked reading by elision. Writing it out is optional but can make the intent clear:
fn make_trimmer() -> Box<dyn for<'a> Fn(&'a str) -> &'a str> {
Box::new(str::trim)
}
fn main() {
let trim = make_trimmer();
let owned = String::from(" padded ");
println!("[{}]", trim(&owned));
println!("[{}]", trim(" literal "));
}The boxed callback works on a borrowed String and on a 'static literal, because it accepts every lifetime. This is the same reason str::trim itself works as a callback: it is declared as taking &'a str and returning &'a str for any 'a.
Closure inference gotcha
A closure bound to a variable gets its signature inferred without the bound in view. The compiler may then infer one specific lifetime for the parameter instead of a higher-ranked one. This commonly bites when the closure returns its argument:
fn call_twice<F>(f: F) -> usize
where
F: for<'a> Fn(&'a str) -> &'a str,
{
let a = String::from("one");
let b = String::from("three");
f(&a).len() + f(&b).len()
}
fn hint<F>(f: F) -> F
where
F: for<'a> Fn(&'a str) -> &'a str,
{
f
}
fn main() {
// let f = |s: &str| s; // may fail: closure infers one lifetime
let f = hint(|s| s); // the bound guides inference
println!("{}", call_twice(f));
}The commented line is the one that tends to produce a "lifetime may not live long enough" error when you use f with two differently-scoped strings. Passing the closure directly to a function with the for<'a> bound, or routing it through an identity function like hint, gives the compiler the signature it needs. Writing the closure inline at the call site, as in the first apply example, always works.
Reading the errors
- E0597 inside a generic function that takes a callback. Check whether the callback's bound uses a lifetime from the function's own parameter list. If the function creates the reference, switch the bound to
for<'a>or elidedFn(&T)form. - "expected a closure that implements
for<'a> Fn(&'a str)but this closure only implementsFn(&str)for one specific lifetime." The closure was inferred with a single lifetime. Move the closure into the call, add ahintfunction, or annotate the parameter type. - "implementation of
Addis not general enough". A trait bound on a reference type was written withoutfor<'a>, or a caller supplies a type whose impl only covers one lifetime. Addfor<'a>on the bound, or fix the impl so it is generic over lifetimes.
Limits worth knowing
- HRTBs are about trait bounds. You cannot write
for<'a>on an arbitrary type or a struct field, apart from function pointer anddyn Fntypes, where it is part of the type itself. - A higher-ranked bound is stronger than an ordinary one. A callback that works for every lifetime also works for one lifetime, but not the other way around. So requiring
for<'a>restricts what callers can pass. A closure that returns a reference captured from outside, for example, will not satisfyfor<'a> Fn(&'a str) -> &'a strunless the return value comes from the argument. - Most application code never needs more than the elided
Fn(&T) -> &Uform. Treat explicitfor<'a>as a tool for generic library code and for bounds on&T.
Exercise
Why does fn run<'a, F: Fn(&'a str) -> usize>(f: F) fail if run calls f(&String::from("x")) internally, while fn run<F: Fn(&str) -> usize>(f: F) succeeds?
Show answer
In the first version 'a is a parameter chosen by the caller, so it must outlive the whole call to run. The temporary String created inside run lives for a shorter time, so borrowing it as &'a str gives E0597. In the second version the elided lifetime in Fn(&str) is higher-ranked, which means F: for<'a> Fn(&'a str) -> usize. The function may therefore pick a fresh, short 'a for each call, and the temporary borrow is valid.
Exercise
Write the bound that says "for every lifetime, a reference to T can be turned into a String" using Into. Then say why T: Into<String> alone is not enough for a function that only has &T values.
Show answer
The bound is for<'a> &'a T: Into<String>. The plain bound T: Into<String> describes converting an owned T, which consumes the value. The function only holds &T, and &T is a different type from T, so it needs its own Into<String> implementation. That implementation must hold for the particular short borrow the function creates, which is why the for<'a> form is required.