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.

RustData Integrity

Code

rustsnippet
32 lines
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

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 =`.