Build a custom iterator
Quick answer
Implement the Iterator trait when you need to generate a sequence from custom state. The iterator's next method controls the next item and when iteration ends.
Maintain progress in next
Set the associated Item type, then implement fn next(&mut self) -> Option<Self::Item>. Return Some for each produced item and None when exhausted. The examples below are fused in behavior: once exhausted they keep returning None, though Iterator alone does not require that for every implementation.
struct Countdown(u32);impl Iterator for Countdown { type Item = u32; fn next(&mut self) -> Option<u32> { if self.0 == 0 { return None; } let n = self.0; self.0 -= 1; Some(n) }}fn main() { for n in Countdown(3) { println!("{n}"); } }Expected stdout (not executed):
321The state decreases on each successful next call.
struct RepeatTwice { left: u8 }impl Iterator for RepeatTwice { type Item = &'static str; fn next(&mut self) -> Option<Self::Item> { if self.left == 0 { None } else { self.left -= 1; Some("tick") } }}fn main() { println!("{}", RepeatTwice { left: 2 }.count()); }Expected stdout (not executed):
2Standard consumers work with the custom iterator.
Common mistake
Forgetting to advance internal state can create an infinite sequence unintentionally.
Try it yourself
Create a finite iterator yielding even numbers from 2 through 10 and test repeated next calls after exhaustion.
Static examples for Rust 1.85.0, edition 2024. Run them locally in a disposable project; ByteMind execution support and these outputs have not been verified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Build a custom iterator — practice quiz
Choose one answer per question. Code examples are predictions; review explanations after attempting them.
A countdown iterator returns Some(3) forever. Which invariant is missing?
Build a custom iterator — example 1. Read the code; do not execute it for this question. Assume the lesson’s stated setup, compatible dependencies and toolchain, and a fresh disposable directory for file-creating examples. ```rust struct Countdown(u32); impl Iterator for Countdown { type Item = u32; fn next(&mut self) -> Option<u32> { if self.0 == 0 { return None; } let n = self.0; self.0 -= 1; Some(n) } } fn main() { for n in Countdown(3) { println!("{n}"); } } ``` What standard output should the program produce if its run succeeds? Ignore Cargo and diagnostic messages.
Build a custom iterator — example 2. Read the code; do not execute it for this question. Assume the lesson’s stated setup, compatible dependencies and toolchain, and a fresh disposable directory for file-creating examples. ```rust struct RepeatTwice { left: u8 } impl Iterator for RepeatTwice { type Item = &'static str; fn next(&mut self) -> Option<Self::Item> { if self.left == 0 { None } else { self.left -= 1; Some("tick") } } } fn main() { println!("{}", RepeatTwice { left: 2 }.count()); } ``` What standard output should the program produce if its run succeeds? Ignore Cargo and diagnostic messages.