Sub topic 13
Higher-ranked bounds beyond Fn: IntoIterator on references
This chapter assumes you know generics, trait bounds, and the Fn(&T) -> &U sugar from the previous chapters. Higher-ranked bounds also appear on traits that have nothing to do with closures. The most common case is a bound on a reference to a generic type.
The problem: the borrow lives inside the function
Suppose you want a function that works with any collection C where iterating over &C yields &i32. A reference type such as &'a C has a lifetime, so the bound has to say which one.
If the function receives c: &C, the caller's lifetime is available to name. If the function owns c and borrows it inside its body, no caller can name that lifetime. It exists only for a few lines of the body. The bound must therefore hold for every lifetime.
Writing the bound with for<'a>
fn sum_all<C>(c: &C) -> i32
where
for<'a> &'a C: IntoIterator<Item = &'a i32>,
{
c.into_iter().sum()
}
fn main() {
let v = vec![1, 2, 3];
println!("{}", sum_all(&v));
}Read the where clause as "for every lifetime 'a, &'a C implements IntoIterator with Item = &'a i32". Vec<i32> satisfies this because the standard library implements IntoIterator for &'a Vec<T> with Item = &'a T for every 'a.
The Item = &'a i32 part ties the item's lifetime to the same 'a as the reference. That tie is why the bound can't be replaced with a plain IntoIterator bound on C. C: IntoIterator would consume the collection and yield owned values.
When a named lifetime fails
The next function owns c and borrows it twice in its body.
fn count_twice<C>(c: C) -> usize
where
for<'a> &'a C: IntoIterator<Item = &'a i32>,
{
let first = (&c).into_iter().count();
let second = (&c).into_iter().count();
first + second
}
fn main() {
println!("{}", count_twice(vec![10, 20, 30]));
}Each &c creates a separate borrow with its own short lifetime. If you wrote fn count_twice<'a, C>(c: C) where &'a C: ..., the caller would pick 'a before the call. 'a would then outlive the whole function body, and c is dropped before the body ends. The compiler would reject &c as not living long enough. With for<'a>, the bound holds for whatever short lifetime each borrow gets.
Common mistakes
- Putting
for<'a>inside the angle brackets, as infn f<for<'a> ...>. The binder belongs in awhereclause or directly in a bound. - Writing
Item = &i32without a lifetime. Elided lifetimes aren't allowed in this position, so name'aand use it on both sides. - Using a higher-ranked bound where one named lifetime would do. If the function only borrows a parameter it received, a named lifetime on that parameter is simpler.
Exercise
Why does fn f<'a, C>(c: C) -> usize where &'a C: IntoIterator<Item = &'a i32> { (&c).into_iter().count() } fail to compile, and what is the fix?
Show answer
The lifetime 'a is a generic parameter, so the caller chooses it, and it must outlive the function body. The borrow &c is local to the body and is dropped before the body ends, so it cannot have lifetime 'a. The fix is to remove 'a from the generics and write the bound as for<'a> &'a C: IntoIterator<Item = &'a i32>, so the bound holds for any lifetime, including the short one of the local borrow.