rust / intermediate
Snippet
Custom Iterator Implementation
Implementing the Iterator trait allows you to create custom iterable types. The Iterator trait requires a next() method that returns Option<Item>. This enables powerful method chaining with filter, map, fold, and other combinators.
snippet.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
struct Counter {count: u32,max: u32,}impl Counter {fn new(max: u32) -> Self {Counter { count: 0, max }}}impl Iterator for Counter {type Item = u32;fn next(&mut self) -> Option<Self::Item> {if self.count < self.max {self.count += 1;Some(self.count)} else {None}}}fn main() {let counter = Counter::new(5);let sum: u32 = counter.filter(|x| x % 2 == 0).sum();println!("Sum of even numbers: {}", sum);}
Breakdown
1
struct Counter { count: u32, max: u32 }
Struct holds current count and maximum value
2
impl Iterator for Counter
Implementing Iterator trait for custom type
3
type Item = u32;
Associated type defines what the iterator yields
4
fn next(&mut self) -> Option<Self::Item>
Returns Some(value) while items remain, None when done