How to Implement Custom Iterators with Complex State

Create a struct to hold state and implement the Iterator trait's next method to define custom iteration logic.

Implement custom iterators with complex state by defining a struct to hold the state and implementing the Iterator trait with a next method that updates that state.

struct Counter {
    count: u32,
    limit: u32,
}

impl Iterator for Counter {
    type Item = u32;

    fn next(&mut self) -> Option<Self::Item> {
        if self.count < self.limit {
            self.count += 1;
            Some(self.count)
        } else {
            None
        }
    }
}

fn main() {
    let counter = Counter { count: 0, limit: 3 };
    for num in counter {
        println!("{num}");
    }
}