Programming Languages
Rust
Subjective
Oct 04, 2025
How do you implement custom iterators in Rust?
Detailed Explanation
Custom iterators in Rust:
• Implement the Iterator trait
• Define associated Item type
• Implement next() method
• Lazy evaluation by default
• Chainable with adapter methods
• Zero-cost abstractions
Iterator trait:
trait Iterator {
type Item;
fn next(&mut self) -> Option;
}
Example - Counter iterator:
struct Counter {
current: usize,
max: usize,
}
impl Counter {
fn new(max: usize) -> Counter {
Counter { current: 0, max }
}
}
impl Iterator for Counter {
type Item = usize;
fn next(&mut self) -> Option {
if self.current < self.max {
let current = self.current;
self.current += 1;
Some(current)
} else {
None
}
}
}
// Usage
let counter = Counter::new(5);
for num in counter {
println!("{}", num); // 0, 1, 2, 3, 4
}
// With iterator adapters
let sum: usize = Counter::new(5)
.map(|x| x * x)
.filter(|&x| x % 2 == 0)
.sum();
println!("Sum of even squares: {}", sum);
Discussion (0)
No comments yet. Be the first to share your thoughts!
Share Your Thoughts