Custom Iterator Fibonacci Sequence
Implement a custom iterator for the Fibonacci sequence with lazy evaluation.
Code
struct Fibonacci {
curr: u64,
next: u64,
}
impl Fibonacci {
fn new() -> Self { Self { curr: 0, next: 1 } }
}
impl Iterator for Fibonacci {
type Item = u64;
fn next(&mut self) -> Option<Self::Item> {
let new = self.curr + self.next;
let old = self.curr;
self.curr = self.next;
self.next = new;
Some(old)
}
}
fn main() {
let fibs: Vec<u64> = Fibonacci::new().take(10).collect();
println!("{:?}", fibs);
}Report a problem with this exampleOpens a pre-filled issue on GitHub.