How to Implement a Custom Iterator in Rust

Create a custom iterator in Rust by defining a struct and implementing the Iterator trait with a next method.

Implement a custom iterator in Rust by defining a struct to hold state and implementing the Iterator trait with a next method that returns Option<T>.

struct Counter {
    count: u32,
}

impl Iterator for Counter {
    type Item = u32;

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

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