Sub topic 10
GATs with lifetime parameters: a lending iterator
This chapter assumes you can write a trait with an associated type, read Iterator<Item = T> bounds, and follow basic borrowing and lifetime rules. You will build a lending iterator, a trait whose items borrow from the iterator itself. You will also see why the where Self: 'a clause is required.
What the lifetime parameter changes
A plain associated type is fixed once per implementation. In impl Iterator for Countdown, Item is u32 for every call to next. It cannot mention a lifetime that belongs to one particular call.
A generic associated type (GAT) with a lifetime parameter removes that limit. Writing type Item<'a> means the trait defines a different item type for each lifetime 'a. The next method then chooses 'a to be the borrow of &mut self. The item can hold a reference into the iterator, and the borrow checker knows the iterator stays borrowed while that item is alive.
Iterator::next cannot do this. Its signature is fn next(&mut self) -> Option<Self::Item>. Self::Item has no way to name the lifetime of the &mut self borrow, so the item cannot borrow from the iterator.
The trait
trait LendingIterator {
type Item<'a>
where
Self: 'a;
fn next<'a>(&'a mut self) -> Option<Self::Item<'a>>;
}There are three parts to read here:
type Item<'a>declares the associated type with a lifetime parameter, in the same place where a generic struct would put it.where Self: 'asays the item type is only defined when the implementing type outlives'a. A later section explains why this is required.fn next<'a>(&'a mut self) -> Option<Self::Item<'a>>uses the same'afor the mutable borrow ofselfand for the item. This is the link that makes the iterator "lend" its items.
A complete implementation: mutable windows
The standard library offers windows for shared slices, but it has no mutable version. A mutable version cannot be written as an Iterator. Consecutive windows overlap, so an Iterator would hand out two live &mut references to the same elements. With a lending iterator, the next window cannot be requested until the previous one is dropped.
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 adds its first element into its second, so the running sum carries forward through the overlapping windows.
Two lifetimes appear in the impl, and they play different roles:
'tis the lifetime of the slice the struct holds. It belongs to the type.'ais the lifetime of one call tonext. It is shorter than or equal to'tand belongs to the borrow of the iterator.
The item is &'a mut [T], not &'t mut [T]. The code reborrows through self, so the window cannot live longer than the call's borrow. Returning &'t mut [T] would be unsound, because it would let you keep a window while calling next again.
Lending in action
The next diagram shows what the borrow checker enforces when you call next.
This is why the while let loop above compiles. The binding w is dropped at the end of each iteration, before the next call to windows.next().
If you try to keep two items at once, the compiler refuses:
let a = windows.next();
let b = windows.next(); // error[E0499]: cannot borrow `windows` as mutable more than once at a time
println!("{:?} {:?}", a, b);That error is the intended behavior. It is what keeps the overlapping windows from aliasing.
Reusing a buffer
Lending also lets an iterator reuse one allocation instead of allocating a fresh value per item. This iterator keeps a String buffer and lends a view of it:
trait LendingIterator {
type Item<'a>
where
Self: 'a;
fn next<'a>(&'a mut self) -> Option<Self::Item<'a>>;
}
struct UpperLines {
lines: Vec<&'static str>,
pos: usize,
buf: String,
}
impl LendingIterator for UpperLines {
type Item<'a> = &'a str where Self: 'a;
fn next<'a>(&'a mut self) -> Option<Self::Item<'a>> {
let line = *self.lines.get(self.pos)?;
self.pos += 1;
self.buf.clear();
self.buf.push_str(&line.to_uppercase());
Some(self.buf.as_str())
}
}
fn main() {
let mut it = UpperLines {
lines: vec!["alpha", "beta"],
pos: 0,
buf: String::new(),
};
while let Some(line) = it.next() {
println!("{line}");
}
}It prints ALPHA and BETA. The call self.buf.clear() is safe because the previous &str must be gone before next can run again. A normal Iterator<Item = &str> could not do this, since every item would point at the same buffer that the next call overwrites.
Why `where Self: 'a` is required
The item type &'a mut [T] is only well-formed if the data it points to lives at least as long as 'a. For the item to be valid, the compiler needs [T]: 'a, which depends on the implementing type outliving 'a.
Without a clause on the trait, the trait would promise that Item<'a> exists for every 'a, including 'static. An implementation could not keep that promise, because WindowsMut<'t, T> is not valid for 'static. The clause where Self: 'a restricts the promise to lifetimes the implementer actually outlives.
The compiler asks for the clause on the trait declaration. If you leave it out, you get an error saying the clause is required, along with the reasoning above. You then write the same clause on the impl, as in type Item<'a> = &'a mut [T] where Self: 'a;.
The clause costs you nothing inside next. The receiver &'a mut self already implies Self: 'a, so the bound holds automatically in the method.
Using a lending iterator generically
You can write generic code over any lending iterator. A function that takes &mut I works well, because the borrow of *iter supplies the 'a:
fn count_remaining<I: LendingIterator>(iter: &mut I) -> usize {
let mut n = 0;
while let Some(_item) = iter.next() {
n += 1;
}
n
}Add it to either program above, with the trait definition in scope, and call count_remaining(&mut windows).
Constraining the item type is harder. You might expect a bound like for<'a> I: LendingIterator<Item<'a> = &'a mut [i32]> to work. In practice the Self: 'a clause is applied to every 'a in the for<'a>, which forces I: 'static. Types such as WindowsMut<'t, T> then fail the bound. This is one of the limitations covered in the last chapter. For now, prefer bounds that do not repeat the item type, or take the iterator by &mut I.
Comparing the two designs
| Question | `Iterator` | `LendingIterator` |
|---|---|---|
| Item type | One fixed type, `Self::Item` | One type per borrow, `Self::Item<'a>` |
| Can items borrow from the iterator? | No | Yes |
| Can you hold several items at once? | Yes | No, each must be dropped first |
| `for` loops and adapters | Supported | Not supported, use `while let` |
| In the standard library | Yes | No, you define it or use a crate |
The last two rows matter in practice. The for loop is defined in terms of IntoIterator and Iterator, so a lending iterator cannot use it. Adapters such as map and filter also need lending versions, and writing them runs into the same limitations on higher-ranked bounds.
Common mistakes
- Returning
&'t mut [T]fromnext. This fails to compile, because the item may not outlive the borrow ofself. - Forgetting
where Self: 'a. The compiler reports that the clause is required on the associated type. - Collecting items into a
Vec. This holds several items at once, so it breaks the lending rule. Copy or clone the data out first. - Expecting
forloops to work. Usewhile let Some(item) = iter.next().
Exercise
In the UpperLines iterator, what would happen if next were declared as fn next(&mut self) -> Option<&'static str> in a normal Iterator implementation, with the item still pointing at self.buf? Why does the LendingIterator version avoid the problem?
Show answer
The code would not compile. Returning a reference into self.buf requires a lifetime tied to the borrow of self, and Iterator::Item cannot name that lifetime. If it were allowed, the caller could keep an item while calling next again, which clears and rewrites the buffer the item points at. The LendingIterator version ties the item to 'a, the borrow of &'a mut self. The compiler therefore rejects any use of an old item after the next call to next.