Skip to content

Implement an Iterator with an Associated Item

The Course
•
30 min study

Today the ledger starts reading input: lines, then values within lines, then whole batches. Each stage produces a sequence, and the standard library already has a large vocabulary for sequences: map, filter, sum, collect, zip and dozens more. Implementing the Iterator trait for your own type plugs it into all of them. You write one method, next; the trait provides more than seventy others built on it.

Iterator has an associated type, Item, and next(&mut self) -> Option<Self::Item>. Each call either yields Some(item) and advances the state, or returns None when the sequence is exhausted. The associated type, rather than a generic parameter like Iterator<T>, says that each iterator type produces exactly one kind of item. That is what lets sum and collect know the element type without annotations. The example below produces a half-open range: it includes next and stops before end.

Predict and run

Which values are produced before the first None? What happens on the call after that?

Predict, then run Rust
struct Steps { next: u32, end: u32 }

impl Iterator for Steps {
    type Item = u32;

    fn next(&mut self) -> Option<Self::Item> {
        if self.next >= self.end {
            return None;
        }
        let value = self.next;
        self.next += 1;
        Some(value)
    }
}
fn main() {
    let mut steps = Steps { next: 2, end: 4 };
    println!("{:?}", steps.next());
    println!("{:?}", steps.next());
    println!("{:?}", steps.next());
    println!("{:?}", steps.next());
}
Check your prediction
Text
Some(2)
Some(3)
None
None

4 is excluded because the range is half-open, and the fourth call stays None because the state no longer changes once next reaches end. The trait does not require that: an iterator may legally return Some again after a None, so your type has to choose. Try replacing the four prints with println!("{}", Steps { next: 2, end: 5 }.sum::<u32>()); and predict the result (9), then try a start equal to the end, which yields nothing and sums to 0.

Adapters for free, and the overflow boundary

Once next exists, every adapter works. The example also runs the iterator right up to u32::MAX, the boundary where a careless implementation would overflow.

Reuse standard adapters on Steps Rust
struct Steps { next: u32, end: u32 }

impl Iterator for Steps {
    type Item = u32;
    fn next(&mut self) -> Option<Self::Item> {
        if self.next >= self.end {
            return None;
        }
        let value = self.next;
        self.next += 1;
        Some(value)
    }
}

fn main() {
    let even: Vec<u32> = Steps { next: 1, end: 10 }.filter(|n| n % 2 == 0).collect();
    println!("even: {even:?}");
    let labels: Vec<String> = Steps { next: 1, end: 4 }
        .zip(["bolt", "nut", "gear", "spring"])
        .map(|(n, name)| format!("{n}.{name}"))
        .collect();
    println!("labels: {labels:?}");
    let top: Vec<u32> = Steps { next: u32::MAX - 2, end: u32::MAX }.collect();
    println!("top: {top:?}");
}
Text
even: [2, 4, 6, 8]
labels: ["1.bolt", "2.nut", "3.gear"]
top: [4294967293, 4294967294]

zip stops as soon as either side is exhausted, so spring is never used. The last line works because next compares before it increments: after yielding u32::MAX - 1, the field becomes u32::MAX, which equals end, and every later call returns before touching it. An inclusive version that tried to yield u32::MAX itself would need care:

Rust
fn next(&mut self) -> Option<u32> {
    if self.next > self.last { return None; }
    let value = self.next;
    self.next += 1; // overflows after yielding u32::MAX
    Some(value)
}

With last set to u32::MAX, the increment after the final item panics with attempt to add with overflow in a debug build, and wraps to 0 in a release build, restarting the sequence. The standard RangeInclusive keeps an extra exhausted flag for exactly this reason.

Tell consumers what you know

The provided methods make cautious assumptions. size_hint defaults to "zero or more, upper bound unknown", so collect cannot reserve the right capacity up front. If your iterator knows its length, say so. Two marker traits make promises explicit: ExactSizeIterator adds len(), and FusedIterator promises that None is permanent, which lets fuse() skip its extra bookkeeping.

Report an exact size and a fused end Rust
use std::iter::FusedIterator;

struct Steps { next: u32, end: u32 }

impl Iterator for Steps {
    type Item = u32;
    fn next(&mut self) -> Option<Self::Item> {
        if self.next >= self.end {
            return None;
        }
        let value = self.next;
        self.next += 1;
        Some(value)
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        let remaining = self.end.saturating_sub(self.next) as usize;
        (remaining, Some(remaining))
    }
}

impl ExactSizeIterator for Steps {}
impl FusedIterator for Steps {}

fn main() {
    let mut steps = Steps { next: 3, end: 7 };
    println!("len before: {}", steps.len());
    steps.next();
    println!("len after one: {}", steps.len());
    println!("backwards range: {}", Steps { next: 9, end: 2 }.len());
}
Text
len before: 4
len after one: 3
backwards range: 0

saturating_sub keeps a backwards range such as 9 to 2 at zero instead of underflowing. These are promises to every consumer. A wrong size_hint cannot cause memory unsafety, but it is a bug: len() would report a false count, and code that sizes a buffer or a progress display from it would be wrong. Implement ExactSizeIterator only when the count is exact.

Items cannot borrow from the iterator itself

The signature fn next(&mut self) -> Option<Self::Item> does not tie Item to the &mut self borrow. So an iterator can yield &'a str slices of data it borrows for 'a, such as the ledger's item list, but it cannot yield references into a buffer it owns and overwrites on each call. That pattern needs a different design, such as BufRead::read_until filling a buffer you pass in, which is what the bounded reader later today does.

Practice

Exercise

Your turn

Implement Countdown { remaining: u32 } that yields its starting value down to 1, then stays exhausted. Collect Countdown { remaining: 3 } and print the vector. Also assert that Countdown { remaining: 0 } yields None immediately, and that a countdown from 1 returns None on both its second and third calls.

Your working space Rust
fn main() {
    // Define Countdown and collect Countdown { remaining: 3 }.
}
Hint 1: the idea

Store the value still to yield. Check for zero first, then yield the current value and subtract one. Checking before subtracting is what keeps a u32 from going below zero.

Hint 2: a first step

Write impl Iterator for Countdown with type Item = u32; and start next with if self.remaining == 0 { return None; }.

Worked solution
Run the solution Rust
struct Countdown { remaining: u32 }

impl Iterator for Countdown {
    type Item = u32;

    fn next(&mut self) -> Option<Self::Item> {
        if self.remaining == 0 { return None; }
        let value = self.remaining;
        self.remaining -= 1;
        Some(value)
    }
}

fn main() {
    assert_eq!(Countdown { remaining: 0 }.next(), None);
    let mut one = Countdown { remaining: 1 };
    assert_eq!((one.next(), one.next(), one.next()), (Some(1), None, None));
    let values: Vec<_> = Countdown { remaining: 3 }.collect();
    println!("{values:?}");
}
Text
[3, 2, 1]

The zero check does two jobs: it stops the subtraction below zero, and because nothing changes once remaining is 0, it makes exhaustion permanent, so impl FusedIterator for Countdown {} would be an honest promise. The tuple assertion evaluates its three calls left to right. The next lesson collects an iterator whose items can fail.

Was this article helpful?

Your response is saved on this device.