Sub topic 3
Fn(&T) and Higher-Ranked Trait Bounds
Prerequisites: ownership, borrowing, lifetime annotations, generics, and the Fn traits.
Function Bounds Hide `for<'a>`
In a function trait bound, an elided input lifetime means “for every possible lifetime.” Therefore:
F: Fn(&str) -> &strmeans approximately:
F: for<'a> Fn(&'a str) -> &'a strThe callable must accept a string slice with any lifetime and return a slice tied to that input.
Closures and Higher-Ranked Inference
This bound lets one closure work with borrows that have different lifetimes:
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() {
println!("{:?}", apply_to_both(|s| s.trim()));
}A bound using one named lifetime can be too restrictive because it may require both calls to use the same lifetime.
Higher-Ranked Bounds Beyond `Fn`
Higher-ranked bounds also work with ordinary traits. This function says that a reference to C can be converted into an iterator for every borrow lifetime:
fn sum_all<C>(collection: &C) -> i32
where
for<'a> &'a C: IntoIterator<Item = &'a i32>,
{
collection.into_iter().sum()
}Higher-Ranked Types and Subtyping
A function that accepts a reference of any lifetime is more general than one that accepts only 'static:
fn takes_static(f: fn(&'static str) -> usize) -> usize {
f("text")
}
fn length(s: &str) -> usize {
s.len()
}
fn main() {
println!("{}", takes_static(length));
}length has a higher-ranked function type, so it can safely be used where only a 'static argument is required.
Diagnosing Errors
The error “implementation of Fn is not general enough” usually means a closure or function was inferred for one lifetime instead of every lifetime. Add an explicit for<'a> bound and ensure the returned reference comes from the input.
Where HRTB Runs Out
HRTBs describe relationships between existing references. They cannot express an iterator whose item lifetime depends on each mutable borrow in the required way. Generic associated types (GATs) solve that lending-iterator pattern by allowing an associated type to have its own lifetime parameter.
Exercise
What does F: Fn(&str) -> &str mean in lifetime terms?
Show answer
It means F: for<'a> Fn(&'a str) -> &'a str: the callable works for every input lifetime and returns a reference tied to that input.