Sub topic 16
Where HRTB runs out: generic associated types and lending iterators
This chapter shows a problem that for<'a> cannot solve and the feature that solves it. You should already know how Iterator works. You should also have read the earlier chapters on for<'a> bounds and on variance, and you should be comfortable with where clauses and associated types.
The problem: an iterator that hands out borrows of itself
A for<'a> bound says "this works for every lifetime 'a". It is a statement about a bound or a function signature. It cannot change the shape of a trait that was defined without a lifetime parameter.
The standard Iterator trait is the clearest case:
trait Iterator {
type Item;
fn next(&mut self) -> Option<Self::Item>;
}Item is one type, chosen once per implementation. It cannot depend on the lifetime of the &mut self borrow in next. So an item can never borrow from the iterator itself. It can only borrow from data the iterator already holds a borrow of, with a lifetime fixed in the impl.
That rules out a mutable sliding window over a slice. Each window overlaps the next one, so the iterator may only give out one window at a time. Here is the natural attempt:
struct WindowsMut<'t, T> {
slice: &'t mut [T],
start: usize,
size: usize,
}
impl<'t, T> Iterator for WindowsMut<'t, T> {
type Item = &'t mut [T];
fn next(&mut self) -> Option<Self::Item> {
let end = self.start.checked_add(self.size)?;
let window = self.slice.get_mut(self.start..end)?;
self.start += 1;
Some(window) // error: lifetime may not live long enough
}
}This does not compile. The Item type promises a borrow that lasts for 't. The code can only produce a borrow that lasts as long as the &mut self it received. If the compiler accepted this, a caller could collect two overlapping &'t mut [T] windows and mutate the same element through both.
Why `for<'a>` cannot fix it
You might try to repair this at the use site with a higher-ranked bound such as for<'a> I: Iterator<Item = &'a mut [T]>. That bound asks for an Iterator whose single Item type equals &'a mut [T] for every 'a at once. No type is equal to all of those types, so no implementation can satisfy it.
The missing piece is in the trait definition. Item needs to be a family of types, one per lifetime. A higher-ranked bound only says something about a trait that already has such a family.
Generic associated types
A generic associated type (GAT) is an associated type that takes its own parameters. Lifetime parameters are the most common kind. GATs have been stable since Rust 1.65. A lending iterator is the standard first example:
trait LendingIterator {
type Item<'a>
where
Self: 'a;
fn next<'a>(&'a mut self) -> Option<Self::Item<'a>>;
}The signature of next ties the item's lifetime 'a to the borrow of self. While the caller holds an item, the iterator stays mutably borrowed. The compiler therefore rejects a second call to next, and the overlapping-window problem cannot occur.
The clause where Self: 'a says the implementing type must outlive 'a. Without it, the declaration could not name types like &'a mut [T], because the compiler could not know the data behind them outlives 'a. For now, treat the clause as required on any GAT that has a lifetime parameter and borrows from self.
Here is WindowsMut implemented against this trait:
trait LendingIterator {
type Item<'a>
where
Self: 'a;
fn next<'a>(&'a mut self) -> Option<Self::Item<'a>>;
}
struct WindowsMut<'t, T> {
slice: &'t mut [T],
start: usize,
size: usize,
}
impl<'t, T> LendingIterator for WindowsMut<'t, T> {
type Item<'a> = &'a mut [T] where Self: 'a;
fn next<'a>(&'a mut self) -> Option<Self::Item<'a>> {
let end = self.start.checked_add(self.size)?;
let window = self.slice.get_mut(self.start..end)?;
self.start += 1;
Some(window)
}
}
fn main() {
let mut data = [1, 2, 3, 4, 5];
let mut windows = WindowsMut { slice: &mut data, start: 0, size: 3 };
while let Some(w) = windows.next() {
w[2] += w[0];
println!("{w:?}");
}
}The program prints:
[1, 2, 4]
[2, 4, 6]
[4, 6, 9]The second window sees the 4 written through the first one. That overlap is the reason this iterator cannot be a normal Iterator.
The next body is almost identical to the failing version. The difference is the return type. Item<'a> is &'a mut [T], and 'a is exactly the lifetime of the &mut self borrow, which is the lifetime the reborrow of self.slice actually has.
Comparing the two traits
| Aspect | `Iterator` | `LendingIterator` |
|---|---|---|
| Item type | One type per implementation | A family of types, one per lifetime |
| Item can borrow from the iterator | No | Yes |
| Two items alive at once | Allowed | Rejected by the borrow checker |
| `for` loop support | Yes | No, use `while let Some(x) = it.next()` |
| `collect`, `map`, `filter` | In the standard library | Not in the standard library |
A for loop desugars to IntoIterator, which is built on Iterator. That is why the example uses while let. The standard library has no lending iterator trait. If you need adapters such as map or filter, check the ecosystem crates for lending or streaming iterators before writing your own.
Where GATs and HRTB meet
GATs do not replace higher-ranked bounds. They give you more places to need one. If a generic function wants to say "every item this lending iterator yields is Debug", it has to quantify over the item's lifetime, which means writing for<'a> I::Item<'a>: Debug.
Choosing between the options
Use a plain Iterator when items can be owned values or can borrow from data that outlives the iterator. This covers almost all cases. Reach for a GAT-based trait only when each item must borrow from the iterator's own state, such as overlapping mutable windows, a line reader that reuses one buffer, or a cursor that exposes its current row. In those cases the cost is the missing for loop and the missing standard adapters, and you accept it in exchange for avoiding a copy or an allocation per item.
Exercise
A colleague writes the bound for<'a> I: Iterator<Item = &'a mut [T]> to accept an iterator of mutable windows. Why can no iterator satisfy it, and what change to the trait makes the idea expressible?
Show answer
Iterator::Item is a single type fixed by each implementation. The bound would need that one type to equal &'a mut [T] for every 'a at once, which no type does. The trait must make Item depend on a lifetime, which a generic associated type does: type Item<'a> where Self: 'a; together with fn next<'a>(&'a mut self) -> Option<Self::Item<'a>>.
Exercise
In the WindowsMut lending iterator, what does the compiler do if you write let a = windows.next(); let b = windows.next(); use(a, b);, and why?
Show answer
It rejects the code. next takes &'a mut self and returns Item<'a>, so a keeps the iterator mutably borrowed while it is alive. The second call needs a new mutable borrow while a is still used later, which breaks the rule of one mutable borrow at a time. This is what prevents two overlapping mutable windows.