rust 32 lines · 6 steps

Building a custom Fibonacci iterator in Rust

Implementing the Iterator trait turns a small struct into something you can loop over and chain with adapters.

Explained by highlit
1/// A custom iterator that yields Fibonacci numbers up to a maximum value.
2pub struct Fibonacci {
3 current: u64,
4 next: u64,
5 max: u64,
6}
7 
8impl Fibonacci {
9 pub fn up_to(max: u64) -> Self {
10 Fibonacci { current: 0, next: 1, max }
11 }
12}
13 
14impl Iterator for Fibonacci {
15 type Item = u64;
16 
17 fn next(&mut self) -> Option<Self::Item> {
18 if self.current > self.max {
19 return None;
20 }
21 let value = self.current;
22 let upcoming = self.current + self.next;
23 self.current = self.next;
24 self.next = upcoming;
25 Some(value)
26 }
27 
28 fn size_hint(&self) -> (usize, Option<usize>) {
29 // We don't know the exact count cheaply, but it's bounded.
30 (0, None)
31 }
32}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Implementing Iterator's next method is all it takes to make a type work with for loops and adapter chains.
  2. 2Holding the current and next values lets each call advance the sequence without recomputing from scratch.
  3. 3Returning None from next signals the end of iteration, while size_hint stays conservative when the count is unknown.

Related explainers

Share this explainer

Here's the card — post it anywhere.

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