How to Use the Iterator Pattern (Beyond std

:iter) in Rust

Implement the Iterator trait on a custom struct by defining the next method to return Option<Self::Item> for custom iteration logic.

To use the Iterator pattern beyond std::iter, implement the Iterator trait on a custom struct by defining the next method to return Option<Self::Item>. This allows your custom type to be consumed by standard iterator adapters like map, filter, and collect.

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 };
    let sum: u32 = counter.take(3).sum();
    println!("Sum: {sum}");
}