How to implement custom iterators

Create a struct and implement the Iterator trait with a next method returning Option to build custom iterators in Rust.

Implement custom iterators by defining a struct to hold state and implementing the Iterator trait with a next method that returns Option<Self::Item>.

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);
    }
}