Sub topic 8
The lending iterator problem
This chapter assumes you can write a trait with an associated type, you know how Iterator::next works, and you understand shared versus mutable borrows and basic lifetime annotations. It explains why a plain associated type cannot express one kind of iterator. The next chapters give the fix.
What `Iterator` promises
Iterator declares one associated type, Item, and one method:
fn next(&mut self) -> Option<Self::Item>;Self::Item is a single type, fixed when the trait is implemented. The &mut self borrow lasts only for the call. The returned Item cannot mention that borrow, because the borrow's lifetime has no name in the trait. As a result, each item must be independent of the iterator that produced it.
That independence is what lets you write iter.collect::<Vec<_>>(). You can hold many items at once, and calling next again does not invalidate the earlier ones.
A case that works: shared windows
Overlapping windows over a slice fit this model. Each item borrows from the underlying slice, not from the iterator.
struct Windows<'t, T> {
slice: &'t [T],
start: usize,
size: usize,
}
impl<'t, T> Iterator for Windows<'t, T> {
type Item = &'t [T];
fn next(&mut self) -> Option<&'t [T]> {
let end = self.start + self.size;
if end > self.slice.len() {
return None;
}
let slice = self.slice;
let window = &slice[self.start..end];
self.start += 1;
Some(window)
}
}
fn main() {
let data = [1, 2, 3, 4];
let all: Vec<&[i32]> = Windows { slice: &data, start: 0, size: 2 }.collect();
println!("{:?}", all);
}The program prints [[1, 2], [2, 3], [3, 4]]. The lifetime 't belongs to the struct, so type Item = &'t [T] is a complete, fixed type. A shared reference is Copy, so handing out overlapping copies is safe.
The case that fails: mutable windows
Now try to yield &mut [T] windows. Consecutive windows overlap: [1, 2] and [2, 3] both contain the element 2. If the iterator could hand out both at once, you would hold two &mut references to the same element, which Rust forbids.
The only safe design ties each window to the borrow of the iterator. The next call to next cannot happen until you have dropped the previous window. An iterator that works this way is a lending iterator.
With Iterator, you would write type Item = &'a mut [T], and 'a would have to come from somewhere. The trait gives you three options, and none of them works:
| Choice for `'a` | Result |
|---|---|
| A lifetime on the impl, such as `'t` | The window outlives the call to `next`, so two windows could be alive together. The compiler rejects the body of `next`. |
| A fresh lifetime on `next` | `Item` is declared once per impl, not once per call, so it cannot depend on a lifetime that exists only in the method. |
| `'static` | The data would have to live forever. |
The compiler's complaint is usually "lifetime may not live long enough" inside next.
What is missing
The shape you want is "for each borrow of self, a different Item type". A plain associated type is one type per implementation. You need an associated type that takes a lifetime parameter, so it becomes a family of types, one for each lifetime.
Generic associated types (GATs) give you the missing parameter. The next chapter introduces their syntax, and the chapter after builds the lending iterator.
Exercise
Why can std::slice::Windows implement Iterator, while a version that yields overlapping &mut [T] windows cannot?
Show answer
Iterator::Item is one fixed type that cannot depend on the borrow of &mut self in next. Shared windows borrow from the underlying slice and can safely overlap, so Item = &'t [T] works. Mutable overlapping windows would alias the same elements, so each window must be tied to the iterator's borrow. A plain associated type has no lifetime parameter to express that.