Sub topic 10
GATs with lifetime parameters: a lending iterator
This chapter assumes you can write traits and generic bounds, read lifetime annotations, and use Iterator. It builds on the previous chapters' generic associated type syntax.
The problem in one sentence
With Iterator, type Item is fixed when you implement the trait. It cannot mention the lifetime of the &mut self borrow in next. So an iterator cannot hand out references into its own state that are only valid until the next call to next.
A lending iterator needs exactly that. Each item borrows from the iterator, and the borrow checker must stop you from holding two items at once. A mutable sliding window is the classic case, because consecutive windows overlap.
Adding a lifetime parameter to the associated type
A generic associated type (GAT) can take its own parameters. Here the parameter is a lifetime:
trait LendingIterator {
type Item<'a>
where
Self: 'a;
fn next<'a>(&'a mut self) -> Option<Self::Item<'a>>;
}Item<'a> is now a family of types, one for each lifetime. The next method links the two. The 'a in &'a mut self is the same 'a in Self::Item<'a>. The returned item therefore keeps the iterator mutably borrowed until the item is dropped.
The where Self: 'a clause is required. Without it the compiler rejects the trait. The next chapter explains why.
Implementing it: mutable windows
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 + self.size;
if end > self.slice.len() {
return None;
}
let window = &mut self.slice[self.start..end];
self.start += 1;
Some(window)
}
}
fn main() {
let mut data = [1, 2, 3, 4];
let mut windows = WindowsMut { slice: &mut data, start: 0, size: 2 };
while let Some(w) = windows.next() {
w[1] += w[0];
}
println!("{:?}", data);
}The program prints [1, 3, 6, 10]. Each window overlaps the previous one, so every step sees the element the last step just changed. That is a running sum.
Two lifetimes appear here, and they mean different things:
'tis how long the original slice is borrowed. It belongs to the struct.'ais how long onenextcall's borrow lasts. It belongs to each item.
Each window is a reborrow of self.slice for 'a, which is at most 't.
What the borrow checker enforces
Try to keep two windows alive at once:
// Does not compile: the first window is still alive
// when the second call to next borrows windows again.
let a = windows.next().unwrap();
let b = windows.next().unwrap();
a[0] = 0;The compiler reports a second mutable borrow of windows. This is the safety guarantee you wanted. If Iterator could return these windows, collect would produce overlapping &mut slices, which is undefined behavior.
Practical notes
- A
forloop does not work with aLendingIterator. It only acceptsIntoIterator. Usewhile let Some(x) = it.next(). - Adapters such as
mapandfilterare not provided. You must write them yourself or use a crate. - Callers that require bounds on the item must use a higher-ranked form such as
for<'a> I::Item<'a>: Debug. The standard library does not yet make this ergonomic.
Exercise
In the WindowsMut example, why can't the same item type be written with a plain associated type such as type Item = &mut [T];?
Show answer
A plain associated type is fixed for the whole implementation and has no name for the lifetime of each &mut self borrow in next. The reference needs a lifetime that differs per call. type Item<'a> provides one, and Self::Item<'a> in the signature ties it to the borrow of self.
Exercise
Change WindowsMut so each window has size 3 and the loop does w[2] += w[1]. Given [1, 2, 3, 4], what does the program print?
Show answer
[1, 2, 5, 9]. The first window [1, 2, 3] makes w[2] equal to 5. The second window [2, 5, 4] makes w[2] equal to 9. There is no third window.