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
Implement Iterator trait with next() method.
Key Concepts
- Read the code carefully and understand the data flow
- Try modifying the example to see how it changes behavior
- Run this code in the Rust Playground
Related Topics
Browse more examples in the iterators category to build a complete understanding of this topic.