Sub topic 13
Higher-ranked bounds beyond Fn: IntoIterator on references
This chapter assumes you know the for<'a> syntax and the Fn(&T) -> &U sugar from the earlier chapters. It also assumes you are comfortable with generics, trait bounds and IntoIterator. Here you will use the same idea on a trait that has nothing to do with closures.
Why the problem shows up outside closures
A higher-ranked trait bound (HRTB) says "this holds for every lifetime 'a". Closures are the most common place to see one, but the need is wider. It appears whenever a generic function must borrow a value of generic type, and the borrow is created inside the function body.
Take a generic container C. To iterate over it without consuming it, you use the IntoIterator implementation for &C. The standard library provides this for &Vec<T>, &HashSet<T>, &BTreeSet<T> and others. The trait implementation belongs to the type &'a C, so the lifetime is part of the type you are bounding.
The simple case: the caller supplies the borrow
If the function receives a reference, the lifetime is already named by the signature:
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));
}The bound reads: "for every lifetime 'a, a shared reference to C with lifetime 'a implements IntoIterator, and its items are &'a i32." Inside the body, c is a &'x C for some anonymous lifetime 'x. The compiler instantiates the bound at 'x, and c.into_iter() type-checks.
In this case, a named parameter would also work:
fn sum_all_named<'a, C>(c: &'a C) -> i32
where
&'a C: IntoIterator<Item = &'a i32>,
{
c.into_iter().sum()
}Both versions compile. The difference appears in the next case.
The case that needs `for<'a>`: the function creates the borrow
Suppose the function takes C by value and borrows it more than once:
fn sum_twice<C>(c: C) -> i32
where
for<'a> &'a C: IntoIterator<Item = &'a i32>,
{
let first: i32 = (&c).into_iter().sum();
let second: i32 = (&c).into_iter().sum();
first + second
}
fn main() {
println!("{}", sum_twice(vec![1, 2, 3]));
}This prints 12. Each &c creates a fresh borrow with a short lifetime that exists only inside sum_twice. The caller cannot know these lifetimes, so the function signature cannot name them.
If you wrote fn sum_twice<'a, C>(c: C) where &'a C: IntoIterator<...>, the lifetime 'a would be chosen by the caller. It would have to outlive the whole call, because every lifetime parameter does. But c is moved into the function and dropped at the end of the body, so no borrow of it can last that long. The compiler would reject &c with an error that c does not live long enough. for<'a> fixes this by moving the choice of lifetime from the caller to the function body.
Bounds on the associated type
Often you do not want to fix Item to a concrete type. You want to say "whatever the items are, they implement Debug". The item type depends on 'a too, so that bound must also be higher-ranked:
use std::collections::BTreeSet;
use std::fmt::Debug;
fn debug_all<C>(c: &C)
where
for<'a> &'a C: IntoIterator,
for<'a> <&'a C as IntoIterator>::Item: Debug,
{
for item in c {
println!("{item:?}");
}
}
fn main() {
debug_all(&vec!["a", "b"]);
let set: BTreeSet<i32> = [3, 1, 2].into_iter().collect();
debug_all(&set);
}There are two bounds, and each has its own for<'a>. The 'a in the first bound is not the same variable as the 'a in the second. Each for<'a> introduces a new name that is scoped to its own bound.
Writing <&'a C as IntoIterator>::Item in full is required here. The shorter form Self::Item or C::Item would not refer to the reference's implementation.
Implied bounds and `C: 'a`
You may wonder why the bound does not say C: 'a. A reference type &'a C is only well-formed when C outlives 'a. Inside a for<'a> bound, the compiler treats that requirement as part of the type, so it quantifies over those lifetimes only. In practice you do not write the outlives bound yourself.
Reading the bound aloud
Use this translation when you meet one in unfamiliar code:
| Written form | Reading |
|---|---|
| `for<'a> &'a C: IntoIterator` | A shared borrow of `C`, for any lifetime, can be iterated. |
| `for<'a> &'a mut C: IntoIterator` | A mutable borrow of `C`, for any lifetime, can be iterated. |
| `for<'a> F: Fn(&'a T) -> &'a U` | `F` accepts a reference of any lifetime and returns one tied to it. |
| `for<'a> <&'a C as IntoIterator>::Item: Debug` | The item type, at every lifetime, implements `Debug`. |
The Fn row is the one you already know. The others use the same quantifier on a different kind of predicate. A bound on &'a C is a statement about a type constructor, and the compiler checks it once for each lifetime it needs.
Common errors
The most frequent error is implementation of IntoIterator is not general enough. It means the caller's concrete type satisfies the bound only for some lifetimes, not all of them. Typical causes:
- A hand-written
impl IntoIterator for &'static MyTypeinstead ofimpl<'a> IntoIterator for &'a MyType. Fix the impl to be generic over the lifetime. - An impl with an extra lifetime tie, for example
impl<'a> IntoIterator for &'a Wrapper<'a>. This forces the borrow and the inner lifetime to be equal, so it is not general over all borrows. Use two lifetimes,impl<'a, 'b> IntoIterator for &'a Wrapper<'b>. - Adding a bound
for<'a> &'a C: IntoIterator<Item = &'a i32>when the real item type is&'a Tfor a genericT. The bound then mentions the wrong type. Make the function generic overTas well.
Where this runs out
for<'a> &'a C: IntoIterator<Item = &'a i32> works because each borrow of the container produces an independent iterator. It cannot describe an iterator whose items borrow from the iterator itself, as with a windows_mut-style adapter that hands out overlapping mutable views. Iterator::next takes &mut self, but its Item type is fixed before that borrow exists, so the item cannot mention the borrow's lifetime. HRTB does not help, because the lifetime is tied to a method call and not to a type. Generic associated types address this, and a later chapter covers them as lending iterators.
Exercise
Why does fn total<'a, C>(c: C) -> i32 where &'a C: IntoIterator<Item = &'a i32> fail to let the body write (&c).into_iter().sum::<i32>(), and what change fixes it?
Show answer
The lifetime 'a is chosen by the caller, so it must outlive the entire call. The body borrows the local c, which is dropped when the function returns, so that borrow cannot have lifetime 'a. Replacing the bound with for<'a> &'a C: IntoIterator<Item = &'a i32> lets the body pick a short lifetime for each borrow, and the code compiles.
Exercise
In debug_all, why does the Debug bound need its own for<'a> instead of reusing the one from the IntoIterator bound?
Show answer
Each for<'a> is scoped to a single bound. The item type <&'a C as IntoIterator>::Item depends on 'a, so the Debug requirement must also hold for every 'a, and it needs its own quantifier.