expression

Custom Iterator implementation — track remaining state

Define the yielded type and the state transition for next. This finite counter advances only while its cursor is below the end. Use an exclusive bound to avoid arithmetic overflow at u32::MAX. Expected stdout (not executed): [40, 41, 42] Common mistake: Forgetting to advance the state on a successful call.

Formal Syntax & Structure

rust syntaxrust
impl Iterator for Tickets { type Item = u32; fn next(&mut self) -> Option<u32> { /* update state */ } }

Working Example

Example Snippetrust
struct Tickets { next: u32, end: u32 }impl Iterator for Tickets {    type Item = u32;    fn next(&mut self) -> Option<u32> {        if self.next >= self.end { return None; }        let ticket = self.next;        self.next += 1;        Some(ticket)    }}fn main() { let tickets: Vec<_> = Tickets { next: 40, end: 43 }.collect(); println!("{tickets:?}"); }
Rust Reference