Creating Custom Iterators
Creating Custom Iterators
struct Counter {
count: usize,
}
impl Counter {
fn new() -> Self { Self { count: 0 } }
}
impl Iterator for Counter {
type Item = usize;
fn next(&mut self) -> Option<Self::Item> {
if self.count < 3 {
self.count += 1;
Some(self.count)
} else {
None
}
}
}
fn main() {
let counter = Counter::new();
let items: Vec<usize> = counter.collect();
println!("Custom iterator output: {:?}", items);
}