How to Implement Iterator for Custom Types

Implement the Iterator trait by defining the Item type and the next method to return Option values.

Implement the Iterator trait for your custom type by defining the Item associated type and the next method.

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