Sub topic 12
Closures and higher-ranked inference
This chapter assumes you know the Fn traits and the for<'a> syntax from the previous chapters.
The closure has no bound to read
A closure's signature is inferred, and the inference depends on where the closure appears. When you pass a closure straight to a function with an Fn(&str) -> &str bound, the compiler reads that bound first. It sees a higher-ranked signature and checks the closure against it. The parameter and the return value get the same fresh lifetime on every call.
When you bind the closure to a variable first, no bound is visible yet. The compiler picks one concrete lifetime for the parameter and treats the returned reference as unrelated to it. The closure then does not satisfy for<'a> Fn(&'a str) -> &'a str, even though its body is fine.
A failing case
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() {
// Does not compile: no expected signature when the closure is defined.
// let f = |s: &str| s.trim();
// println!("{:?}", apply_to_both(f));
// Compiles: the bound is visible at the call site.
println!("{:?}", apply_to_both(|s| s.trim()));
}Depending on the shape of the closure, the error reads either lifetime may not live long enough inside the closure body or implementation of Fn is not general enough at the call.
Fix: pin the signature with a helper
If you need the closure in a variable, pass it through an identity function whose only job is to carry the bound. The closure is then checked against for<'a> Fn(&'a str) -> &'a str at the point where it is written.
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 constrain<F>(f: F) -> F
where
F: for<'a> Fn(&'a str) -> &'a str,
{
f
}
fn main() {
let f = constrain(|s| s.trim());
println!("{:?}", apply_to_both(f));
}This prints (10, 7). Note that constrain is an ordinary generic function. Nothing in it is special except the bound.
Why return types make it harder
Closures with only an argument, such as |s: &str| s.len(), usually work either way. The returned usize does not borrow from s, so there is nothing to connect. Problems appear when the return value carries the argument's lifetime. The closure syntax has no way to name that link. You cannot write for<'a> |s: &'a str| -> &'a str, so the expected bound is the only way to supply it.
Summary of the rules
| Situation | Higher-ranked? |
|---|---|
| Closure passed directly to a function with an `Fn(&T) -> &U` bound | Yes, taken from the bound |
| Closure stored in a `let` first, returning a borrow of its argument | No, error |
| Closure stored in a `let` first, returning an owned value | Usually yes, for the argument |
| Closure passed through a `constrain`-style helper | Yes |
| Named `fn` item | Yes |
Exercise
Why does let f = |s: &str| s.trim(); apply_to_both(f); fail while apply_to_both(|s| s.trim()) succeeds?
Show answer
In the second form the compiler sees the bound for<'a> Fn(&'a str) -> &'a str while checking the closure, so it infers a signature that ties the returned &str to the argument for every lifetime. In the first form the closure is inferred alone, with no expected signature, so the returned reference is not tied to the argument's lifetime. The closure then fails the higher-ranked bound when it is passed in.
Exercise
Name two ways to keep a closure in a variable and still pass it to a function that requires for<'a> Fn(&'a str) -> &'a str.
Show answer
Wrap it in an identity helper such as constrain that carries the higher-ranked bound, or replace the closure with a named function fn(&str) -> &str.