How to implement Iterator trait

Implement the Iterator trait by defining the Item type and the next method to return Option<Self::Item>.

Implement the Iterator trait by defining the Item associated type and the next method to return 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
        }
    }
}