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 std::any::{Any, TypeId}; use std::collections::HashMap; pub trait Event: Any {
A type-safe event bus in Rust
type-erasure
trait-objects
downcasting
Advanced
8 steps
ruby
class Order class InvalidTransition < StandardError; end TRANSITIONS = {
A state machine for order transitions in Ruby
state-machine
data-driven
error-handling
Intermediate
8 steps
rust
use std::cmp::Ordering; pub struct PrefixIndex { entries: Vec<String>,
Prefix search with binary partitioning in Rust
binary-search
sorting
case-insensitive
Intermediate
7 steps
python
import time import threading from enum import Enum from functools import wraps
Building a circuit breaker in Python
circuit-breaker
resilience
decorators
Advanced
7 steps
rust
use std::cmp::Ordering; use std::str::FromStr; #[derive(Debug, Clone, PartialEq, Eq)]
Parsing and ordering semantic versions in Rust
parsing
trait-implementation
ordering
Intermediate
8 steps
rust
use axum::{ extract::State, routing::{get, post, MethodRouter}, Json, Router,
Self-documenting routes in Axum
builder-pattern
closures
shared-state
Intermediate
8 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.