Sub topic 8
The lending iterator problem
This chapter shows a case where the associated type Item is not expressive enough. You need to be comfortable with Iterator, associated types as covered earlier in this tutorial, and lifetime elision on &mut self methods.
What Iterator promises
The Iterator trait looks like this:
trait Iterator {
type Item;
fn next(&mut self) -> Option<Self::Item>;
}Item is chosen once per implementing type. For Countdown it is u32, and for std::slice::Iter<'a, T> it is &'a T. The type does not change from one call of next to the next.
The &mut self in next has its own lifetime, and that lifetime exists only for the duration of the call. The return type Option<Self::Item> cannot mention it, because Item was fixed before any call to next existed. The signature therefore says that the item the caller gets back is not borrowed from the iterator for that call.
Written out with elided lifetimes made explicit, the signature is:
fn next<'a>(&'a mut self) -> Option<Self::Item>;The lifetime 'a appears only in the argument. Nothing connects it to the result.
This works for most iterators. A Vec<T> iterator yields owned values. A slice::Iter<'a, T> yields references, but those borrow from the underlying slice (lifetime 'a on the iterator type), not from the iterator value itself. Each item can be used after the iterator moves on or is dropped.
An iterator that cannot be written
Suppose you want to visit every overlapping window of a slice, with mutable access. For [1, 2, 3, 4] and a window size of 2, the windows are [1, 2], [2, 3] and [3, 4]. The standard library has windows for shared references but no mutable counterpart. Here is the obvious 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 + self.size;
if end > self.slice.len() {
return None;
}
let window = &mut self.slice[self.start..end];
self.start += 1;
Some(window)
}
}This does not compile. The compiler reports that the returned value borrows from self and that the anonymous lifetime of &mut self must outlive 't. The slice is borrowed for 't, but the only thing next can borrow is *self, and that borrow lasts for the call's lifetime 'a, which is shorter than 't.
Why the compiler is right
Suppose the code were accepted. The Iterator contract allows a caller to hold several items at once:
// Hypothetical: this would be legal for any Iterator
let a = windows.next().unwrap();
let b = windows.next().unwrap();
a[1] = 0; // a covers indices 0..2
b[0] = 9; // b covers indices 1..3Both a and b would be live &mut references to index 1. That breaks Rust's rule that a mutable reference is the only live path to its data. The same problem shows up in any adapter that stores items, such as collect::<Vec<_>>(), peekable, or zip.
The pattern itself is fine
The aliasing problem exists only when items can outlive the next call. If each window must be dropped before the next call to next, the code is sound. You can write that as an ordinary method, because lifetime elision on a method ties the returned reference to the &mut self borrow:
struct WindowsMut<'t, T> {
slice: &'t mut [T],
start: usize,
size: usize,
}
impl<'t, T> WindowsMut<'t, T> {
fn next(&mut self) -> Option<&mut [T]> {
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, and the overlap lets the running total carry forward. The borrow checker accepts this because the returned &mut [T] keeps windows mutably borrowed. You cannot call next again until w is no longer used.
An iterator that hands out items borrowed from itself is called a lending iterator. The inherent method above works, but it is not part of any trait. That has practical consequences:
- A
forloop only acceptsIntoIterator, so you are limited towhile let. - Adapters such as
map,filterandenumeratedo not exist for it. - A generic function cannot say "give me anything that lends items".
To write such a function you need a trait, and the trait needs an associated type that can depend on a lifetime.
What the trait would need to say
The missing piece is an item type that varies per call. In pseudocode:
// Pseudocode: not valid Rust with a plain associated type
trait LendingIterator {
type Item<'a>; // depends on the borrow
fn next<'a>(&'a mut self) -> Option<Self::Item<'a>>;
}Here Item takes a lifetime parameter, so it is a family of types, one for each 'a. For WindowsMut, Item<'a> would be &'a mut [T]. This is a generic associated type, or GAT. The syntax and the extra where clause it requires are the subject of the next two chapters, so only the idea matters here: the item's lifetime is tied to the borrow in next.
How people worked around it
Before GATs were stabilized in Rust 1.65, and still in code that does not use them, these were the common workarounds:
| Workaround | Cost |
|---|---|
| Return owned items (clone or allocate) | An allocation or copy per item. `BufRead::lines` returns a new `String` for every line. |
| Pass in a buffer (`read_line(&mut buf)`) | Not an iterator, so there are no adapters and no `for` loops. |
| Index-based access (`for i in 0..n { data[i..i + 2] }`) | Manual bounds management, and it does not compose through generic code. |
| Inherent `next` method, as above | Works for one concrete type but cannot be used generically. |
| Higher-ranked trait bound encodings (`for<'a> Trait<'a>`) | Verbose, with poor error messages and limited inference. |
The BufRead::lines case is the one most programs meet. Each call allocates a fresh String, even though a lending iterator could reuse one buffer and let you look at each line in turn.
Which iterators are not affected
Not every iterator that yields references has this problem. It is worth knowing why, so you can recognize when you do have it.
slice::Iterandslice::windowsyield shared references. A shared reference isCopy, so any number of overlapping items can coexist. The items borrow from the slice, not from the iterator.slice::chunks_mutyields&mutitems. The windows never overlap, and the iterator splits its slice withsplit_at_mutand moves the remainder out, so each item can carry the full'tlifetime.
You have the lending iterator problem when both of these are true:
- Items borrow from the iterator's own state, such as a buffer or a slice that is reused.
- Later items overlap or reuse the storage of earlier ones.
Summary of the problem
Iterator::next takes &mut self and returns Self::Item, and Item is one fixed type that cannot mention the lifetime of that borrow. Items can therefore never borrow from the iterator itself. That is what lets callers hold many items at once. A lending iterator gives that up in exchange for borrowing from its own state, and expressing it in a trait needs an associated type that takes a lifetime parameter.
Exercise
A colleague writes impl<'t, T> Iterator for WindowsMut<'t, T> { type Item = &'t mut [T]; ... } for overlapping mutable windows, and the compiler rejects next. Explain why in terms of what Self::Item can and cannot depend on, and why accepting it would be unsound.
Show answer
Item is a single type fixed by the impl, and the &mut self borrow in next has a lifetime that exists only for that call. The body can only borrow from *self for that call's lifetime, which is shorter than 't, so it cannot produce &'t mut [T]. If the compiler allowed it, a caller could call next twice and keep both items, which would be two live &mut references to the overlapping element. A trait can only allow this safely if Item is tied to the borrow of self, which needs an associated type with a lifetime parameter.
Exercise
slice::windows and slice::chunks_mut both implement Iterator with reference items. Why do they not have the lending iterator problem?
Show answer
windows yields shared references, which are Copy, so overlapping items are allowed and they can borrow from the underlying slice rather than from the iterator. chunks_mut yields mutable references, but the chunks never overlap, and it splits off each chunk with split_at_mut, so every item gets the full lifetime of the original slice borrow without borrowing from the iterator.