Sub topic 16
Where HRTB runs out: generic associated types and lending iterators
This chapter assumes you know for<'a> bounds, the Iterator trait, and how &mut borrows work. It shows a problem that higher-ranked bounds cannot solve and the feature that does.
The limit of `for<'a>`
A higher-ranked bound says "this works for every lifetime". It constrains how a caller uses a type or function. It cannot change the shape of a trait.
Here is Iterator:
trait Iterator {
type Item;
fn next(&mut self) -> Option<Self::Item>;
}Item has no lifetime parameter. Each implementor picks one Item type, and that type cannot mention the borrow of &mut self in next. So an iterator cannot hand out references into its own buffer. Each call to next would need to return a borrow tied to that call, and Item has nowhere to name it.
No bound on the caller's side fixes this, because the missing lifetime is in the trait definition.
Generic associated types
A generic associated type (GAT) is an associated type with its own parameters. It has been stable since Rust 1.65. Giving Item a lifetime parameter lets each call to next produce a differently scoped item:
trait LendingIterator {
type Item<'a>
where
Self: 'a;
fn next<'a>(&'a mut self) -> Option<Self::Item<'a>>;
}The 'a in next is the borrow of self, and Item<'a> can use it. The clause where Self: 'a is required. It says the iterator must outlive the borrow, which keeps Item<'a> well-formed.
A working lending iterator
slice::windows yields shared windows. A mutable version would give overlapping &mut windows, which Iterator forbids. A lending iterator allows it, because each window must be dropped before the next call to next.
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 start = self.start;
let size = self.size;
self.start += 1;
self.slice.get_mut(start..)?.get_mut(..size)
}
}
fn main() {
let mut data = [1, 2, 3, 4];
let mut windows = WindowsMut { slice: &mut data, start: 0, size: 2 };
while let Some(win) = windows.next() {
win[1] += win[0];
println!("{win:?}");
}
}This prints [1, 3], [3, 6] and [6, 10]. Each window overlaps the previous one, and each sees the writes made through it.
Costs of the GAT approach
forloops do not work, because they are built onIterator. You needwhile let.- Adapters such as
mapandfiltermust be rewritten for the new trait. - Bounds on a GAT are awkward. You can write
for<'a> I::Item<'a>: Debug, which is where HRTB reappears, but some patterns still hit compiler limits.
Choosing between them
| Situation | Tool |
|---|---|
| Accept a closure that works on any borrowed input | `for<'a>` bound, usually via `Fn(&T)` |
| Require a trait on references of any lifetime | `for<'a>` in a `where` clause |
| A trait method returns data borrowed from `&mut self` | GAT with a lifetime parameter |
Exercise
Why can the standard Iterator trait not offer a windows_mut method that returns overlapping &mut windows, and how does a lending iterator avoid the problem?
Show answer
Iterator::Item is one type that cannot depend on the borrow of &mut self in next. Items would therefore have to outlive that borrow, so two overlapping &mut windows could be alive at once and alias the same elements. A lending iterator's Item<'a> is tied to the borrow of self in next. The borrow checker therefore requires each window to be dropped before the next call to next.