Sub topic 12
Closures and higher-ranked inference
This chapter assumes you can read for<'a> Fn(&'a str) -> &'a str and know that Fn(&str) -> &str expands to that form. It covers how the compiler decides whether a closure is higher-ranked, and why the same closure can compile in one position and fail in another.
A closure has one signature, chosen at its definition
A closure is not generic. The compiler picks one signature for it where it is written, and it does so from the expected type if one is available.
- A closure passed directly to a function with an
Fnbound is checked against that bound. If the bound isfor<'a> Fn(&'a str) -> &'a str, the compiler reads the parameter and return types from it, and the closure becomes higher-ranked. - A closure bound to a
letvariable has no expected type. The compiler infers the signature from the body. For a reference parameter it may make the parameter higher-ranked, but it picks a lifetime for the return type that is not tied to the parameter.
The second case is the source of most "implementation of Fn is not general enough" errors.
The working case: pass the closure inline
This reuses apply_to_both from earlier in the tutorial. The function calls f with a borrow of a local String and then with a 'static literal, so F must accept any lifetime.
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 closure has no type annotations. The compiler takes s: &'a str and the return type &'a str from the bound, and s.trim() type-checks against them.
The failing case: store the closure first
Now move the closure into a let.
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 f = |s: &str| s.trim();
// error: lifetime may not live long enough
let r = apply_to_both(f);
println!("{r:?}");
}This does not compile. The annotation s: &str makes the parameter accept any lifetime. The return type, however, is an inference variable that the compiler solves from the body. Nothing says it equals the parameter's lifetime, so the closure does not implement for<'a> Fn(&'a str) -> &'a str.
Without the : &str annotation, the let version fails earlier with "type annotations needed", because s.trim() needs to know the type of s. In both versions the cause is the same: no expected type reached the closure when it was defined.
Three fixes
- Pass the closure inline, as in the working case.
- Use a named function. Elision on
fn trim_it(s: &str) -> &strproduces a single lifetime shared by argument and result, and the function item is higher-ranked. - Route the closure through an identity helper that carries the bound.
The helper gives the compiler the expected type that a bare let lacks:
fn constrain<F>(f: F) -> F
where
F: for<'a> Fn(&'a str) -> &'a str,
{
f
}
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 f = constrain(|s| s.trim());
println!("{:?}", apply_to_both(&f));
println!("{:?}", apply_to_both(f));
}&f works as the first argument because a shared reference to a closure that implements Fn also implements Fn. The closure is checked against the bound inside constrain, so it is higher-ranked when it reaches apply_to_both.
| Approach | Where the signature comes from | Higher-ranked? | Column | Column |
|---|---|---|---|---|
| Inline closure, no annotations | The `Fn` bound at the call site | Yes | ||
| `let f = \ | s: &str\ | s.trim();` | The body, with a free return lifetime | Not for the return |
| `let f = constrain(\ | s\ | s.trim());` | The bound on `constrain` | Yes |
| Named `fn` with elided lifetimes | The function signature | Yes |
A second failure: the closure captures one lifetime
A closure can also fail the bound for a different reason. The bound says the closure must work for every lifetime, but the closure may have captured something tied to one specific lifetime.
fn call_with_temp<F>(mut f: F)
where
F: FnMut(&str),
{
let temp = String::from("temp");
f(&temp);
}
fn main() {
let mut kept: Vec<&str> = Vec::new();
// error: the borrowed `s` cannot be stored in `kept`
call_with_temp(|s| kept.push(s));
println!("{}", kept.len());
}FnMut(&str) expands to for<'a> FnMut(&'a str). The argument is only valid during one call, but kept holds &str values of a single fixed lifetime that outlives the call. Pushing s would let the borrow of temp escape, so the compiler rejects it. Here the closure is inline and the bound was applied correctly. The error is real, and no annotation will remove it.
The fix is to store owned data:
fn call_with_temp<F>(mut f: F)
where
F: FnMut(&str),
{
let temp = String::from("temp");
f(&temp);
}
fn main() {
let mut kept: Vec<String> = Vec::new();
call_with_temp(|s| kept.push(s.to_string()));
println!("{}", kept.len());
}Alternatively, change the function so it takes a single lifetime parameter, for example F: FnMut(&'a str) with temp replaced by a value that lives for 'a. That is a different contract, and it only helps if the caller can supply such a value.
Telling the two failures apart
- If the closure only uses its argument and returns something derived from it, suspect inference. The closure was defined without an expected type. Pass it inline or add
constrain. - If the closure stores its argument somewhere that outlives the call, the bound is working as intended. Clone the data or change the design.
- If the error mentions
'staticor "one specific lifetime" for the closure's argument, check whether aletannotation like|s: &'static str|or a captured variable pinned the lifetime.
Exercise
This code fails with "lifetime may not live long enough". Without changing run, make it compile and say why your change works.
fn run<F>(f: F) -> usize
where
F: for<'a> Fn(&'a [i32]) -> &'a i32,
{
let v = vec![4, 9, 2];
*f(&v) as usize
}
fn main() {
let first = |xs: &[i32]| &xs[0];
println!("{}", run(first));
}
Show answer
Pass the closure inline: run(|xs| &xs[0]). Alternatively, define a helper fn constrain<F>(f: F) -> F where F: for<'a> Fn(&'a [i32]) -> &'a i32 { f } and write let first = constrain(|xs| &xs[0]);. Both work because the closure is then checked against the higher-ranked bound where it is defined. In the original, |xs: &[i32]| &xs[0] is bound by let with no expected type, so the return lifetime is inferred separately from the parameter lifetime. The closure therefore does not implement for<'a> Fn(&'a [i32]) -> &'a i32.