Sub topic 14
Writing your own iterator
This chapter assumes you know the Iterator trait's next method, the difference between iter, iter_mut and into_iter, and how adapters and consumers work. You also need basic generics, Option, and struct definitions.
What you need to implement
The Iterator trait has one required method, next. It also has one associated type, Item, which is the type of value the iterator yields. Every other method, such as map, filter, sum and collect, has a default implementation built on next.
trait Iterator {
type Item;
fn next(&mut self) -> Option<Self::Item>;
// dozens of provided methods
}next returns Some(item) while values remain and None when the iterator is finished. The iterator itself holds the state that tracks its position, so next takes &mut self.
A countdown iterator
This type stores the next number to yield. Each call to next updates that state.
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 sum_of_squares: u32 = Countdown(3).map(|n| n * n).sum();
println!("{}", sum_of_squares); // 14
}Countdown(3) yields 3, 2, 1, then None. Because we implemented Iterator, we can call map and sum on it without writing them. The squares are 9, 4 and 1, which add up to 14.
Using it in a for loop
Any type that implements Iterator also works in a for loop, because for calls IntoIterator::into_iter on its input. A blanket implementation makes every iterator its own IntoIterator.
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() {
for n in Countdown(3) {
println!("{}", n);
}
let evens: Vec<u32> = Countdown(6).filter(|n| n % 2 == 0).collect();
println!("{:?}", evens); // [6, 4, 2]
}Common errors
| Mistake | Symptom | Fix |
|---|---|---|
| Forgetting `type Item` | Compile error about a missing associated type | Add `type Item = ...;` in the `impl` block |
| Not updating state in `next` | Infinite loop | Change a field on every call that returns `Some` |
| Using `&self` in `next` | Signature mismatch with the trait | Use `&mut self` |
| Never returning `None` | Consumers like `sum` and `collect` never finish | Return `None` once the data runs out |
Some consumers need a finite iterator. Use take(n) to cap an iterator that never ends.
Decision guide
Write a custom iterator when the sequence comes from your own state, such as a countdown, a generated series or a walk over a custom data structure. If you only need to transform an existing collection, adapters on iter() are shorter.
Exercise
Write an iterator Evens that starts at 0 and yields 0, 2, 4, and so on, with no end. Use it to print the first four values.
Show answer
struct Evens(u32);
impl Iterator for Evens {
type Item = u32;
fn next(&mut self) -> Option<u32> {
let current = self.0;
self.0 += 2;
Some(current)
}
}
fn main() {
for n in Evens(0).take(4) {
println!("{}", n); // 0, 2, 4, 6
}
}
take(4) stops the otherwise infinite iterator after four items.
Exercise
Why does next take &mut self instead of &self?
Show answer
Each call must change the iterator's internal state, such as a counter or position, so that the next call returns a different value. A shared reference would not allow that change.