Custom Iterator for Fibonacci Numbers
Implement the Iterator trait to produce a lazy Fibonacci sequence, showing how infinity can be represented without allocating a collection.
Code
struct Fibonacci {
current: u64,
next: u64,
remaining: usize,
}
impl Fibonacci {
fn new(remaining: usize) -> Self {
Fibonacci { current: 0, next: 1, remaining }
}
}
impl Iterator for Fibonacci {
type Item = u64;
fn next(&mut self) -> Option<u64> {
if self.remaining == 0 {
return None;
}
let value = self.current;
let following = self.current + self.next;
self.current = self.next;
self.next = following;
self.remaining -= 1;
Some(value)
}
}
fn main() {
let sum: u64 = Fibonacci::new(10).filter(|n| n % 2 == 0).sum();
println!("even fibonacci sum = {sum}");
}Report a problem with this exampleOpens a pre-filled issue on GitHub.