Sub topic 15
Case study: implementing Iterator
This chapter assumes you know how to define and implement a trait, what default methods are, and how associated types work. The Iterator trait combines all three, so it makes a good case study.
The trait in brief
Iterator has one associated type and one required method. Everything else is a default method.
type Itemis the type of each value the iterator produces.fn next(&mut self) -> Option<Self::Item>returnsSome(value)while values remain andNonewhen the iterator is finished.
The standard library supplies dozens of default methods built on next, such as map, filter, take, sum, and collect. You get all of them by writing only next.
Implementing it
This iterator counts down from a starting number to 1.
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]. The next method takes &mut self because the iterator keeps its position inside itself. Each call changes that state. When the counter reaches 0, next returns None.
The collect call is a default method. It calls next repeatedly until it sees None and gathers the results into a Vec<u32>.
Why an associated type
A type has one natural way to iterate, so Countdown always yields u32. An associated type states this once, in the impl. A generic trait such as Iterator<T> would let one type implement the trait many times with different T values. Callers would then have to name the type everywhere. The previous chapters on associated types and generic traits cover this trade-off.
Using the default methods
Because Countdown implements Iterator, adapter methods work on it directly. Adapters are lazy. They do no work until something consumes the iterator.
The consumer, sum, drives the chain. Each call to next pulls one value back through the stages.
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(5)
.filter(|n| n % 2 == 0)
.map(|n| n * 2)
.sum();
println!("{total}");
}The even values are 4 and 2. Doubled, they are 8 and 4, so the program prints 12.
Common errors
- Forgetting
mut. Callingnextdirectly needslet mut it = Countdown(3);, becausenexttakes&mut self. - Never returning
None. An iterator that never ends makescollectandsumloop forever. Usetake(n)to limit it. - Expecting adapters to run on their own. A chain such as
.map(...)with no consumer does nothing, and the compiler warns that iterators are lazy. - Wrong
Itemtype. The return type ofnextmust beOption<Self::Item>. A mismatch withtype Itemis a compile error.
Exercise
Write next for a struct Evens { current: u32, max: u32 } that yields 0, 2, 4, and so on, stopping once the value would exceed max. What does Evens { current: 0, max: 6 }.collect::<Vec<_>>() return?
Show answer
Use if self.current > self.max { None } else { let v = self.current; self.current += 2; Some(v) }, with type Item = u32. The result is [0, 2, 4, 6].