RRust By Example
advancedIterators

Custom Iterator

Implement the Iterator trait for custom types.

Custom Iterator

Implement the Iterator trait for custom types.

Difficulty

Advanced

Code

rust
struct Counter {
    count: u32,
    max: u32,
}

impl Counter {
    fn new(max: u32) -> Counter {
        Counter { count: 0, max }
    }
}

impl Iterator for Counter {
    type Item = u32;

    fn next(&mut self) -> Option<u32> {
        if self.count < self.max {
            self.count += 1;
            Some(self.count)
        } else {
            None
        }
    }
}

fn main() {
    let sum: u32 = Counter::new(5).sum();
    println!("sum: {}", sum);

    let pairs: Vec<(u32, u32)> = Counter::new(3)
        .zip(Counter::new(3).skip(1))
        .collect();
    println!("{:?}", pairs);
}

Explanation

This example demonstrates how to use custom iterator in Rust. Read the code carefully to understand the flow. Pay attention to where values are created, borrowed, moved, or consumed.

Key Concepts

  • Rust's strong type system catches errors at compile time
  • Ownership and borrowing rules ensure memory safety
  • Pattern matching makes code expressive and exhaustive

Related Topics

Browse more examples in the iterators category to build a complete understanding of this topic.

More Iterators Examples