Sub topic 15
Case study: implementing Iterator
This chapter assumes you know how to define and implement a trait, how default methods work, and what an associated type is. It uses Iterator to show how those pieces fit together in the standard library. You should also be comfortable with lifetimes in struct definitions for the borrowing example.
The trait in two pieces
Iterator has one associated type and one required method. Everything else has a default body.
trait Iterator {
type Item;
fn next(&mut self) -> Option<Self::Item>;
// dozens of default methods: map, filter, take, sum, collect, ...
}next returns Some(item) while there are items and None when the sequence is finished. It takes &mut self because producing an item changes the iterator's position. That is why you must write let mut it = ... before calling next yourself.
Item is an associated type, not a generic parameter, because a given iterator type yields exactly one kind of item. A Countdown produces u32 values and nothing else. If Iterator were Iterator<T>, one type could implement it several times, and type inference would often need annotations at every call site.
A minimal implementation
struct Countdown(u32);
impl Iterator for Countdown {
type Item = u32;
fn next(&mut self) -> Option<u32> {
if self.0 == 0 {
None
} else {
self.0 -= 1;
Some(self.0 + 1)
}
}
}
fn main() {
let v: Vec<u32> = Countdown(3).collect();
println!("{v:?}");
}This prints [3, 2, 1]. You wrote two items, Item and next, and collect came from a default method. The next section shows how much else arrives with it.
What the default methods give you
The default methods fall into two groups.
| Group | Examples | Behavior |
|---|---|---|
| Adapters | `map`, `filter`, `take`, `skip`, `zip`, `enumerate`, `chain` | Return a new iterator. Do no work until polled. |
| Consumers | `collect`, `sum`, `count`, `fold`, `last`, `any`, `all` | Call `next` repeatedly and produce a final value. |
Because every default method is written in terms of next, your type works with all of them.
struct Countdown(u32);
impl Iterator for Countdown {
type Item = u32;
fn next(&mut self) -> Option<u32> {
if self.0 == 0 {
None
} else {
self.0 -= 1;
Some(self.0 + 1)
}
}
}
fn main() {
let total: u32 = Countdown(10)
.filter(|n| n % 2 == 0)
.map(|n| n * n)
.sum();
println!("{total}");
}The output is 220, which is 100 + 64 + 36 + 16 + 4. The filter and map calls only build wrapper structs. sum drives the whole pipeline by calling next until it sees None.
What a for loop does
A for loop calls IntoIterator::into_iter on its operand, then calls next until None.
Every Iterator automatically implements IntoIterator through a blanket implementation that returns self. That is why for n in Countdown(3) works without extra code.
An infinite and fallible sequence
An iterator does not need to end. It also does not need to hold a collection. It can compute each item from its state.
struct Fib {
a: u64,
b: u64,
}
impl Fib {
fn new() -> Self {
Fib { a: 0, b: 1 }
}
}
impl Iterator for Fib {
type Item = u64;
fn next(&mut self) -> Option<u64> {
let out = self.a;
let sum = self.a.checked_add(self.b)?;
self.a = self.b;
self.b = sum;
Some(out)
}
}
fn main() {
let first: Vec<u64> = Fib::new().take(10).collect();
println!("{first:?}");
}This prints [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]. The ? operator works on Option, so an overflow in checked_add ends the sequence with None instead of panicking. The cost is that the iterator stops one item early, because it computes the next sum before returning the current value. Use take or take_while to bound an infinite iterator before calling a consumer such as collect. Calling collect on an unbounded iterator never finishes.
Iterating over borrowed data
Real collections usually hand out references. This needs a lifetime on the iterator struct and an Item that borrows from the collection.
struct Playlist {
songs: Vec<String>,
}
struct SongIter<'a> {
songs: &'a [String],
pos: usize,
}
impl<'a> Iterator for SongIter<'a> {
type Item = &'a String;
fn next(&mut self) -> Option<Self::Item> {
let song = self.songs.get(self.pos)?;
self.pos += 1;
Some(song)
}
}
impl Playlist {
fn iter(&self) -> SongIter<'_> {
SongIter { songs: &self.songs, pos: 0 }
}
}
impl<'a> IntoIterator for &'a Playlist {
type Item = &'a String;
type IntoIter = SongIter<'a>;
fn into_iter(self) -> SongIter<'a> {
self.iter()
}
}
fn main() {
let list = Playlist {
songs: vec![String::from("Intro"), String::from("Outro")],
};
for song in &list {
println!("{song}");
}
println!("{}", list.iter().count());
}Three details matter here.
SongIterholds a shared slice, which isCopy. The returned&'a Stringis tied to the playlist's lifetime'a, not to the&mut selfborrow ofnext. This is why callers can keep several items at once.- Implementing
IntoIteratorfor&Playlistis what makesfor song in &listcompile. The standard library follows the same convention:iter()borrows,iter_mut()borrows mutably, andinto_iter()on the owned value consumes it. - Borrowing is safe because the compiler refuses to let you modify
listwhile aSongIteris alive.
Common errors
- Forgetting
mut. Callingnextor usingby_refneeds a mutable binding. Adapter chains passed straight to a consumer don't, because the temporary is owned. - Expecting adapters to run.
list.iter().map(|s| println!("{s}"));does nothing, and the compiler warns that iterators are lazy. Add a consumer such asfor_eachor aforloop. - Reusing a consumed iterator. Methods such as
sumandcollecttakeselfby value. Create a new iterator, or useby_ref()to consume part of one and keep the rest. - Calling
nextafterNone. The trait does not promise that a finished iterator stays finished. An implementation may returnSomeagain. Callfuse()if you need the guarantee, or implementFusedIteratorwhen your type never resumes. - Missing
size_hint. The default hint is(0, None).collectstill works, but it cannot pre-allocate. Overridesize_hintwhen you know the length, as an exact count forCountdown.
Why this design works
Iterator shows how the trait features combine. The associated type fixes the output type. The single required method keeps implementations small. The default methods turn that one method into a full toolkit. The IntoIterator blanket implementation connects iterators to for loops. Each adapter is a generic struct that wraps another iterator, so the compiler monomorphizes a whole chain into one specialized loop with no dyn overhead.
Exercise
Write an iterator Evens that yields the even numbers from 0 up to but not including a limit stored in the struct. What does Evens { next: 0, limit: 7 }.collect::<Vec<u32>>() return, and why can you call .map(|n| n + 1) on it without writing any extra code?
Show answer
Define struct Evens { next: u32, limit: u32 } and implement Iterator with type Item = u32;. In next, return None if self.next >= self.limit. Otherwise save self.next, add 2 to it, and return Some(saved). The call returns [0, 2, 4, 6]. map is a default method on Iterator, and it is written in terms of next. Any type that implements next therefore gets map, filter, sum, and the other defaults without further code.
Exercise
Why does SongIter return &'a String from next even though next receives &mut self with a shorter lifetime?
Show answer
The struct stores songs: &'a [String], a shared reference that is Copy. Reading self.songs.get(...) copies out a reference that lives for 'a, not for the borrow of self. The returned item is therefore tied to the playlist, and the caller can hold several items while still calling next.