Sub topic 14
Higher-ranked trait bounds with for<'a>
This chapter assumes you can read lifetime annotations on functions, know what Fn closures are, and understand where clauses. Higher-ranked trait bounds (HRTBs) are rarely written by hand. You need them when a closure must accept a reference whose lifetime the callee picks, not the caller.
The problem: who chooses the lifetime?
A normal lifetime parameter is chosen by the caller. In fn longest<'a>(...), the caller's references fix what 'a is. Now consider a function that takes a closure and calls it with a reference created inside the function:
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()));
}Here apply decides which string the closure sees. The caller of apply cannot name that lifetime, because it does not exist yet at the call site. A bound like F: Fn(&'a str) -> &'a str with 'a declared on apply would be wrong. It would force one specific 'a, chosen by the caller, for every call the closure receives.
Reading for<'a>
for<'a> means "for every possible lifetime 'a". The bound F: for<'a> Fn(&'a str) -> &'a str says that F must work no matter how long the input reference lives, and the output has the same lifetime as the input.
The word "higher-ranked" refers to this quantifier. The lifetime is bound inside the trait bound itself, not on the function.
The sketch below shows the contrast.
You usually get it for free
The compiler adds for<'a> for you in the common sugar forms. These two bounds mean the same thing:
fn call_with_ref<F>(f: F) -> usize
where
F: Fn(&str) -> usize,
{
let owned = String::from("temporary");
f(&owned)
}
fn call_with_ref_explicit<F>(f: F) -> usize
where
F: for<'a> Fn(&'a str) -> usize,
{
let owned = String::from("temporary");
f(&owned)
}
fn main() {
println!("{}", call_with_ref(|s| s.len()));
println!("{}", call_with_ref_explicit(|s| s.len()));
}The elision rules from earlier in this tutorial apply inside the parentheses of Fn(...). Each elided input lifetime becomes a fresh for<'a> lifetime, and a single input lifetime is copied to the output. So Fn(&str) -> &str is already higher-ranked. You write for<'a> explicitly only when elision cannot express the relationship, for example when two inputs and the output must share a lifetime, or when you write bounds on other traits.
When it goes wrong
A closure whose signature is pinned to one lifetime does not satisfy a higher-ranked bound. Two common triggers:
- Annotating a closure parameter with a type that comes from an outer scope, so the closure only accepts that one lifetime.
- Returning a reference that does not come from the input, such as a captured
&'static stror a value borrowed from outside, where the bound promised the output tied to the input.
The error messages usually mention "implementation of FnOnce is not general enough" or "expected closure signature for<'a> fn(&'a str) -> _". Both mean the closure was inferred for one lifetime and the bound demands all of them. Fixes are to let the compiler infer the parameter type from the bound (pass the closure directly to the function) or to write a named function instead of a closure.
Summary
for<'a>quantifies a lifetime inside a bound: the type must work for every'a.- Use it when the callee, not the caller, creates the reference passed to a closure.
- Elision in
Fn(&T) -> &Talready inserts it, so explicitfor<'a>is rare.
Exercise
In fn apply<F>(f: F) where F: for<'a> Fn(&'a str) -> &'a str, why would declaring fn apply<'a, F>(f: F) where F: Fn(&'a str) -> &'a str break a call to f with a local String?
Show answer
With 'a declared on apply, the caller chooses it, and it must outlive the whole function body. A reference to a local String created inside apply cannot live that long, so the compiler rejects the call. The for<'a> form lets apply pick a fresh, shorter lifetime for each call.
Exercise
Does F: Fn(&str) -> &str need an explicit for<'a>? Why or why not?
Show answer
No. Elision gives the single input reference a fresh lifetime and copies it to the output, which makes the bound higher-ranked automatically. It is equivalent to for<'a> Fn(&'a str) -> &'a str.