Implementing Custom Iterators
Hard
+4 pts
🎯 In Python, you make any object iterable by implementing __iter__ and __next__:
class Countdown:
def __init__(self, start):
self.current = start
def __iter__(self):
return self
def __next__(self):
if self.current <= 0:
raise StopIteration
val = self.current
self.current -= 1
return val
Or more commonly, you use a generator:
def countdown(start):
while start > 0:
yield start
start -= 1
Rust uses the same idea — a trait with a next() method — but the payoff is bigger. Implement one method, and you get 70+ iterator methods (.map(), .filter(), .take(), .sum(), .collect(), etc.) for free.
The Iterator trait
To make your type iterable, implement the Iterator trait:
struct Countdown {
current: u32,
}
impl Iterator for Countdown {
type Item = u32;
fn next(&mut self) -> Option<Self::Item> {
if self.current > 0 {
let val = self.current;
self.current -= 1;
Some(val)
} else {
None
}
}
}
Two …
Login to see the full exercise.
Topics