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}");
}How it works
Custom Iterator for Fibonacci Numbers reduces to the functions new, next and main.
Putting it to use
The primary signature is fn new(remaining: usize) -> Self
Running the file prints labeled results such as even fibonacci sum = — each operation’s effect is visible in the output.
The sequence new lives in main; running the file triggers it.
Core lines
let sum: u64 = Fibonacci::new(10).filter(|n| n % 2 == 0).sum();
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 new(remaining: usize) -> Self {
Fibonacci { current: 0, next: 1, remaining }
}
Interactive Tools for This Topic
Number Base ConverterConvert arbitrary-size integers between binary, octal, decimal, hexadecimal, and base 36 with digit validation and signed input support.Number to WordsConvert an integer up to 999,999,999,999 into US English words, using the short scale and a minus prefix for negative values.Roman Numeral ConverterConvert integers between 1 and 3999 to Roman numerals and back, rejecting malformed numeral forms.Scientific Notation ConverterConvert numbers between plain decimal and scientific notation, optionally fixing the significant digits and splitting out the mantissa and exponent.
FAQ
- What does Custom Iterator for Fibonacci Numbers print when run?
- Execute the whole file; each printed line is prefixed with a label like `even fibonacci sum =`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.