Sub topic 10
Reading and writing for<'a>
This chapter assumes you know basic lifetime annotations, generics with trait bounds, and the Fn traits. The previous chapter showed that a lifetime parameter chosen by the caller is sometimes too rigid. Here you learn the syntax that fixes it.
What for<'a> means
A higher-ranked trait bound (HRTB) says that a bound holds for every lifetime, not for one particular lifetime. You write it with for<'a> in front of the bound:
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).
Read the bound as: "F is a function that, for any lifetime 'a you pick, accepts a &'a str and returns a &'a str." The function body picks two different lifetimes. One is the short borrow of the local owned. The other is the 'static borrow of the literal. Both calls are valid because f works for every 'a.
Why a named parameter fails
Suppose you declare the lifetime on the function instead:
fn apply_to_both<'a, F: Fn(&'a str) -> &'a str>(f: F) -> (usize, usize)Now the caller chooses 'a, and it must outlive the whole call. The local owned is created inside the body, so no caller-chosen lifetime can cover a borrow of it. The compiler rejects f(&owned). With for<'a>, the body picks the lifetime for each call.
Where the quantifier sits
for<'a> introduces 'a only within the bound it prefixes. The scope is the part after it:
F: for<'a> Fn(&'a str) -> &'a strquantifies'aover the wholeFnbound.'ais not visible outside that bound. You cannot use it elsewhere in the signature.- The ordinary
fn name<'a>form quantifies at the function level, so the caller fixes'a.
You can introduce more than one lifetime, as in for<'a, 'b> Fn(&'a str, &'b str) -> &'a str. The bound then holds for every pair of lifetimes, and the return value is tied only to 'a.
Reading checklist
When you meet a bound with for<'a>, ask three questions:
- Which type or trait is being bounded? In the example,
F. - Where does
'aappear? In the argument and the return type, which links them. - Who needs to pick
'a? The code that callsf, once per call.
Most of the time you will not write for<'a> yourself. The next chapter shows that Fn(&str) -> &str expands to exactly this bound through lifetime elision. You write it explicitly when elision cannot express what you need.
Exercise
In fn run<F>(f: F) where F: for<'a> Fn(&'a str) -> &'a str, who chooses 'a for each call to f inside run, and why does that let run pass a borrow of a local String?
Show answer
The body of run chooses 'a separately for each call. The bound promises that f works for every lifetime, so a short borrow of a local String is valid. A lifetime parameter named on run would be chosen by the caller and would have to outlive the call, which rules out borrows of locals.