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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Implementing Iterator lets a custom type plug into for-loops, map, take, and the rest of Rust's iterator ecosystem for free.
- 2Storing just enough state — here two numbers — is often all a sequence generator needs.
- 3checked_add plus the ? operator gives you graceful termination on overflow instead of a panic or silent wraparound.
Related explainers
rust
use serde::Deserialize; #[derive(Debug, Deserialize)] #[serde(untagged)]
Parsing flexible JSON shapes with serde
deserialization
enums
json
Intermediate
6 steps
rust
use std::cmp::{Ordering, Reverse}; use std::collections::BinaryHeap; use std::fs::File; use std::io::{self, BufRead, BufReader, BufWriter, Lines, Write};
K-way merge of sorted logs in Rust
binary-heap
k-way-merge
streaming-io
Intermediate
8 steps
rust
use axum::{ extract::{Path, State}, response::sse::{Event, KeepAlive, Sse}, };
Streaming import progress with SSE in Axum
server-sent-events
streams
watch-channel
Advanced
7 steps
rust
use std::f64::consts::PI; #[derive(Debug, Clone, Copy)] pub struct LatLng {
Building geographic bounding boxes in Rust
geospatial
value-types
option
Intermediate
7 steps
rust
use chrono::{Duration, NaiveDate}; #[derive(Debug)] pub struct DateRange {
Parsing and iterating date ranges in Rust
error-handling
iterators
parsing
Intermediate
7 steps
rust
use std::collections::VecDeque; use std::sync::{Arc, Condvar, Mutex}; use std::time::{Duration, Instant};
Building a counting semaphore in Rust
concurrency
synchronization
condition-variable
Advanced
9 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/a-fibonacci-iterator-in-rust-explained-rust-1ece/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.