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 axum::{extract::{Path, State}, http::StatusCode, Json}; use dashmap::DashMap; use serde::Serialize; use std::sync::Arc;
Request coalescing in an Axum handler
caching
concurrency
request-coalescing
Advanced
8 steps
javascript
import { useReducer, useEffect } from "react"; const initialState = { status: "idle", data: null, error: null };
Building a data-fetching hook in React
custom-hooks
usereducer
data-fetching
Intermediate
9 steps
rust
use std::net::Ipv4Addr; use std::str::FromStr; #[derive(Debug, Clone, Copy)]
Parsing and matching IPv4 CIDR ranges in Rust
bitwise-operations
parsing
error-handling
Intermediate
8 steps
rust
use std::sync::OnceLock; static CRC_TABLE: OnceLock<[u32; 256]> = OnceLock::new();
Table-driven CRC32 with lazy init in Rust
checksums
lazy-initialization
lookup-tables
Intermediate
8 steps
rust
use axum::{ body::Body, extract::Path, http::{header, HeaderMap, HeaderValue, StatusCode},
HTTP range requests for video streaming in Axum
http-range-requests
streaming
async-io
Advanced
8 steps
rust
use std::sync::mpsc; use std::thread; use std::time::Duration;
Running work with a timeout in Rust
concurrency
channels
timeout
Intermediate
7 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.