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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Implementing Iterator's next method is all it takes to make a type work with for loops and adapter chains.
- 2Holding the current and next values lets each call advance the sequence without recomputing from scratch.
- 3Returning None from next signals the end of iteration, while size_hint stays conservative when the count is unknown.
Related explainers
rust
use std::collections::HashMap; use std::sync::{Arc, Mutex}; use std::thread;
Aggregating metrics across threads in Rust
concurrency
shared-state
mutex
Intermediate
7 steps
rust
use std::sync::{mpsc, Arc, Mutex}; use std::thread; use std::time::Duration;
Building a thread pool in Rust
concurrency
channels
thread-pool
Advanced
9 steps
rust
use std::time::Instant; use tracing::info; pub struct Timer {
A scope-guard timer with Drop in Rust
raii
drop-guard
timing
Intermediate
7 steps
rust
use std::collections::HashMap; pub struct Memoizer<K, V, F> { cache: HashMap<K, V>,
A generic memoizer in Rust
memoization
generics
caching
Intermediate
6 steps
javascript
const transitions = { cart: { checkout: 'shipping' }, shipping: { submitAddress: 'payment', back: 'cart' }, payment: { submitPayment: 'review', back: 'shipping' },
A finite state machine for checkout flow
state-machine
event-driven
data-driven-design
Intermediate
7 steps
rust
use std::collections::HashMap; #[derive(Debug, Clone)] struct Order {
Aggregating Rust data with fold and entry
fold
hashmap
ownership
Intermediate
6 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/building-a-custom-fibonacci-iterator-in-rust-explained-rust-638b/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.