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);
}What the code does
Count the functions new, next and main as the entire surface area of Custom Iterator Fibonacci Sequence.
Applying it
Signature: fn new() -> Self
Execute the file and main walks through new, in that order.
Statements that matter
let fibs: Vec<u64> = Fibonacci::new().take(10).collect();
fn new() -> Self { Self { curr: 0, next: 1 } }
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)
}
Interactive Tools for This Topic
FAQ
- How do you run Custom Iterator Fibonacci Sequence?
- The file is self-contained: run it directly, no dependencies to install beforehand.
Report a problem with this exampleOpens a pre-filled issue on GitHub.