rust 27 lines · 6 steps

A Fibonacci iterator in Rust

Implementing the Iterator trait turns a two-field struct into a lazy, overflow-safe Fibonacci sequence.

Explained by highlit
1pub struct Fibonacci {
2 current: u64,
3 next: u64,
4}
5 
6impl Fibonacci {
7 pub fn new() -> Self {
8 Fibonacci { current: 0, next: 1 }
9 }
10}
11 
12impl Default for Fibonacci {
13 fn default() -> Self {
14 Self::new()
15 }
16}
17 
18impl Iterator for Fibonacci {
19 type Item = u64;
20 
21 fn next(&mut self) -> Option<u64> {
22 let value = self.current;
23 self.next = self.current.checked_add(self.next)?;
24 self.current = self.next - self.current;
25 Some(value)
26 }
27}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Implementing Iterator lets a custom type plug into for-loops, map, take, and the rest of Rust's iterator ecosystem for free.
  2. 2Storing just enough state — here two numbers — is often all a sequence generator needs.
  3. 3checked_add plus the ? operator gives you graceful termination on overflow instead of a panic or silent wraparound.

Related explainers

Share this explainer

Here's the card — post it anywhere.

A Fibonacci iterator in Rust — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code