Sub topic 11
Fn(&T) is sugar for a higher-ranked bound
This chapter assumes you can read basic lifetime annotations, write generic functions with trait bounds, and know the Fn, FnMut and FnOnce traits. You have seen that for<'a> lets a bound hold for every lifetime. Here you learn that you rarely type it, because the compiler inserts it for you.
The rule
Inside the parenthesized sugar of Fn, FnMut, FnOnce and fn pointer types, elided lifetimes become higher-ranked. Each elided lifetime in the arguments is a fresh lifetime bound by for<...> on that bound. The elision rules you know from functions then decide how the return type connects to the arguments.
These two functions are identical:
fn call_sugar<F>(f: F) -> usize
where
F: Fn(&str) -> usize,
{
let owned = String::from("abc");
f(&owned) + f("literal")
}
fn call_explicit<F>(f: F) -> usize
where
F: for<'a> Fn(&'a str) -> usize,
{
let owned = String::from("abc");
f(&owned) + f("literal")
}
fn main() {
println!("{}", call_sugar(|s| s.len()));
println!("{}", call_explicit(|s| s.len()));
}Both print 10. The first call to f passes a borrow of a local String. The second passes a 'static literal. The two borrows have different lifetimes, so the bound must accept any lifetime.
Why a named lifetime is different
Compare the sugar with a lifetime parameter on the function:
fn call_fixed<'a, F>(f: F) -> usize
where
F: Fn(&'a str) -> usize,
{
let owned = String::from("abc");
f(&owned) // error[E0597]: `owned` does not live long enough
}This version does not compile. The caller picks 'a, so 'a outlives the whole function body. owned is dropped before the function returns, so &owned cannot last for 'a. The bound says "F accepts &'a str for one particular 'a". The sugar version says "F accepts &str for every lifetime". A function that must be called with a short local borrow needs the second form.
How elision works inside the parentheses
The usual elision rules apply to the arguments and the return type, with one difference: there is no self.
| Written bound | Expands to | Notes |
|---|---|---|
| `Fn(&str) -> usize` | `for<'a> Fn(&'a str) -> usize` | The output has no lifetime, so nothing links to it. |
| `Fn(&str) -> &str` | `for<'a> Fn(&'a str) -> &'a str` | One input lifetime, so the output reuses it. |
| `Fn(&str, &str) -> usize` | `for<'a, 'b> Fn(&'a str, &'b str) -> usize` | Two independent lifetimes. |
| `Fn(&str, &str) -> &str` | Error E0106 | Two input lifetimes, so the output is ambiguous. |
| `Fn() -> &str` | Error E0106 | No input lifetime to borrow from. |
When elision is ambiguous, name the lifetimes yourself with for<'a>:
fn pick<F>(f: F) -> usize
where
F: for<'a> Fn(&'a str, &'a str) -> &'a str,
{
let left = String::from("left side");
let r = f(&left, "right");
r.len()
}
fn main() {
println!("{}", pick(|a, b| if a.len() >= b.len() { a } else { b }));
}This prints 9. Both arguments share 'a, and the compiler shrinks the longer borrow to match the shorter one, as in the covariance chapter. If you only want the output tied to the first argument, write for<'a> Fn(&'a str, &str) -> &'a str. The second &str is still elided, so it gets its own fresh lifetime.
Where the sugar applies
The same expansion happens in every position that uses the parenthesized form:
- Generic bounds:
F: Fn(&T) -> U. - Trait objects:
Box<dyn Fn(&str) -> &str>. - Opaque types in argument and return position:
impl Fn(&str) -> &str. - Function pointer types:
fn(&str) -> &str.
This return-position example compiles because the closure's signature is taken from the impl Fn bound:
fn make_trimmer() -> impl Fn(&str) -> &str {
|s| s.trim()
}
fn main() {
let trim = make_trimmer();
let owned = String::from(" padded ");
println!("[{}]", trim(&owned));
println!("[{}]", trim(" literal "));
}The returned closure works on a local String and on a literal. If the bound had been Fn(&'static str) -> &'static str, the first call would be rejected.
The same rule covers other elided lifetimes in the arguments, such as Fn(std::cell::Ref<i32>), where the hidden lifetime in Ref is also fresh per call.
What the sugar does not cover
- Type parameters. In
F: Fn(&T) -> &T, the reference lifetime is higher-ranked, butTis fixed for the function. IfTitself contains a lifetime, such asT = &'x str, that'xis a single lifetime chosen by the caller. The bound isfor<'a> Fn(&'a &'x str). The'avaries and the'xdoes not. - Trait objects' own lifetime. In
Box<dyn Fn(&str) -> &str>, thedyntype has a separate default object lifetime bound, usually'staticin aBox. That bound says how long the closure's captures live. It has nothing to do with the higher-ranked argument lifetime. - Non-
Fntraits.Iterator,IntoIteratorand your own traits have no parenthesized sugar. A bound like&'a C: IntoIteratorneeds an explicitfor<'a>, which a later chapter covers. - Other generic traits.
Fn<(&str,)>is the unstable desugared form, and elision does not apply there.
Reading the errors
Two errors point back to this chapter:
- E0106, missing lifetime specifier, inside an
Fn(...)bound. Elision found zero or several input lifetimes. Addfor<'a>and name the lifetimes, as inpickabove. - E0597,
xdoes not live long enough, where a closure-taking function has a named'aon the bound. Check whether the bound should be higher-ranked. If the function creates the borrow itself, it should.
A third error, "implementation of Fn is not general enough", arises when a closure was inferred for one lifetime but the bound demands all lifetimes. The next chapter covers it.
Exercise
Which of these bounds is NOT higher-ranked over the reference lifetime, and what happens if the function body calls f(&String::from("x"))? (a) F: Fn(&str) -> usize (b) F: for<'a> Fn(&'a str) -> &'a str (c) fn g<'a, F: Fn(&'a str) -> usize>(f: F)
Show answer
Only (c). Its 'a is a parameter chosen by the caller, so it outlives the function body. Calling f(&String::from("x")) fails with E0597 because the temporary String does not live as long as 'a. Bounds (a) and (b) accept a borrow of any lifetime, so the call compiles. In (a) the compiler inserts for<'a> through elision.
Exercise
The bound F: Fn(&str, &str) -> &str fails to compile. Rewrite it so the output is tied only to the first argument.
Show answer
F: for<'a> Fn(&'a str, &str) -> &'a str. The first argument and the output share 'a, and the second &str is elided to its own fresh lifetime. With two elided inputs and no self, elision cannot pick a lifetime for the output, so you must name one.