Sub topic 14
Writing your own iterator
This chapter assumes you know the Iterator trait and its next method, the difference between iter, iter_mut and into_iter, and basic lifetimes. You also need to be comfortable with Option and with adapters such as map and take. Here you will implement Iterator for your own types and see what the compiler gives you in return.
What you must write
Iterator has one required item for you to supply: next. It also has an associated type, Item, which names what the iterator yields. Every other method (map, filter, sum, zip and dozens more) has a default implementation built on next.
Calling next returns Some(item) while items remain. When the sequence ends, it returns None. A for loop is a repeated call to next that stops at the first None.
A first iterator: state in a struct
An iterator is a value that remembers where it is. The state lives in the struct's fields, and next takes &mut self so it can update 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 sum_of_squares: u32 = Countdown(3).map(|n| n * n).sum();
println!("{}", sum_of_squares); // 14
}Countdown(3) yields 3, 2, 1. The map and sum calls come from the trait's default methods, and you wrote none of them.
Each call to next changes the struct, so an iterator is used up as you go. To walk the sequence again, create a new Countdown.
An infinite iterator
next does not have to ever return None. An infinite iterator is fine as long as the caller bounds it, usually with take, take_while or find.
struct Fibonacci {
a: u64,
b: u64,
}
impl Fibonacci {
fn new() -> Self {
Fibonacci { a: 0, b: 1 }
}
}
impl Iterator for Fibonacci {
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> = Fibonacci::new().take(10).collect();
println!("{:?}", first); // [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
}The ? operator works on Option inside next. If checked_add returns None, the function returns None and the sequence ends. That makes this iterator finite in practice. It stops cleanly just before u64 would overflow, instead of panicking in debug builds or silently wrapping in release builds.
The cost is that it stops one term early, because the term it was about to return is dropped along with the failed sum. A custom iterator should always decide what happens at its limits.
Iterating over borrowed data
The harder case is an iterator over a collection you own. The iterator must borrow from the collection, so it needs a lifetime parameter. It also needs a position to track progress.
struct Playlist {
songs: Vec<String>,
}
struct PlaylistIter<'a> {
songs: &'a [String],
pos: usize,
}
impl<'a> Iterator for PlaylistIter<'a> {
type Item = &'a String;
fn next(&mut self) -> Option<&'a String> {
let item = self.songs.get(self.pos)?;
self.pos += 1;
Some(item)
}
}
impl Playlist {
fn iter(&self) -> PlaylistIter<'_> {
PlaylistIter { songs: &self.songs, pos: 0 }
}
}
impl<'a> IntoIterator for &'a Playlist {
type Item = &'a String;
type IntoIter = PlaylistIter<'a>;
fn into_iter(self) -> PlaylistIter<'a> {
self.iter()
}
}
fn main() {
let playlist = Playlist {
songs: vec!["Intro".to_string(), "Overture".to_string(), "Hi".to_string()],
};
for song in &playlist {
println!("{}", song);
}
let long = playlist.iter().filter(|s| s.len() > 2).count();
println!("{} long titles", long); // 2 long titles
}Three details matter here.
Itemis&'a String, tied to the lifetime'aof the borrow of the playlist, not to the lifetime of&mut selfinnext. The returned reference points into the playlist's data, so it can outlive thenextcall.self.songsis a shared slice, which isCopy. That is whyget(self.pos)can hand out a reference with lifetime'awhilenextonly has a short-lived&mut self. If you stored&'a mut [T]instead, the compiler would refuse to return items, and you would needunsafeorslice::split_first_mut. That is why writing a mutable borrowing iterator by hand is harder than a shared one.- Implementing
IntoIterator for &'a Playlistis what makesfor song in &playlistwork. Aforloop callsinto_iteron whatever you give it.
The standard library follows the same pattern. Vec<T> implements IntoIterator three times: for Vec<T>, &Vec<T> and &mut Vec<T>. Those are the into_iter, iter and iter_mut styles from earlier in this tutorial.
Helping the adapters: size_hint and ExactSizeIterator
size_hint returns (lower, upper) bounds on how many items remain, where the upper bound is an Option. The default is (0, None), which is always correct but unhelpful. collect uses the hint to reserve capacity up front, so a good hint avoids repeated reallocation.
If you know the exact count, override size_hint and add ExactSizeIterator, which gives you len().
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 size_hint(&self) -> (usize, Option<usize>) {
let n = self.0 as usize;
(n, Some(n))
}
}
impl ExactSizeIterator for Countdown {}
fn main() {
let c = Countdown(5);
println!("{}", c.len()); // 5
let v: Vec<u32> = c.collect();
println!("{:?}", v); // [5, 4, 3, 2, 1]
}ExactSizeIterator::len checks that the lower and upper bounds are equal. A wrong size_hint is not undefined behavior, because the trait is safe. But it breaks the contract, and code relying on it may panic or behave oddly. Only claim an exact size when it is true.
Other traits worth knowing
| Trait | What it adds | When to implement it |
|---|---|---|
| `DoubleEndedIterator` | `next_back`, which enables `rev()` | The sequence can be consumed from both ends cheaply |
| `ExactSizeIterator` | `len()` | The exact remaining count is known |
| `FusedIterator` | A promise that `next` returns `None` forever after the first `None` | You want to guarantee it explicitly |
Plain iterators are allowed to return Some again after returning None. Adapters such as fuse() exist to guard against that. If your next keeps returning None once finished, as Countdown does, you are fine in practice.
Common mistakes
- Forgetting to advance state. If
nextdoes not change the struct, it returns the same item forever, andcollectnever finishes. - Unbounded infinite iterators. Calling
sum,countorcollecton an infinite iterator loops forever, or exhausts memory. Always bound it first. - Off-by-one when decrementing. In
Countdown, the value must be read after the decrement (self.0 + 1) or saved in a local variable before it. Write a quick test for the first and last items. - Putting the wrong lifetime on
Item. If you writeOption<&String>innextand the signature elides to the&mut selflifetime, the compiler reports that the lifetime may not live long enough. Name the'aexplicitly, as inPlaylistIter. - Implementing
Iteratoron the collection itself. IfPlaylistimplementedIterator, iterating would consume or mutate the playlist. Keep the collection and its iterator as separate types.
Exercise
In the Playlist example, why is the Item type &'a String instead of &String tied to the lifetime of &mut self in next, and what would go wrong with the second choice?
Show answer
Items point into the playlist's data, which lives for 'a, not into the iterator. If Item were tied to the short borrow of &mut self, each item would block the next call to next, because the previous item would still hold a mutable borrow of the iterator. Patterns like let a = it.next(); let b = it.next(); and collect would fail to compile. Using 'a lets items outlive individual next calls, as long as the playlist itself stays borrowed.
Exercise
What should size_hint return for Countdown(4) before any items are consumed, and what extra trait can you implement once it does?
Show answer
It should return (4, Some(4)), since exactly four items remain. With an exact hint you can implement ExactSizeIterator, which provides len().