Behavioral Patterns in Rust
local graph
Chapter 15 — Behavioral Patterns in Rust
Section titled “Chapter 15 — Behavioral Patterns in Rust”Acta non verba. (Deeds, not words.)
The previous chapters explored how Rust structures data and organizes code without inheritance. Now attention turns to behavior: how objects communicate, how algorithms encapsulate, how responsibilities distribute across a system. The Gang of Four catalog of behavioral patterns includes Strategy, Observer, State, Command, Iterator, Visitor, and others. These patterns manage complex control flow, encapsulate algorithms, and coordinate interactions between objects.
In object-oriented languages, behavioral patterns rely heavily on interfaces, abstract classes, and dynamic dispatch. Objects collaborate through abstract interfaces, enabling late binding and runtime flexibility. Rust offers both familiar translations of these patterns and distinctly different approaches that leverage its ownership system and type-level features. Some patterns translate almost directly. Others transform significantly. A few dissolve entirely into language features that make the pattern unnecessary.
Behavioral patterns in Rust often become simpler than their OOP counterparts. Strategy reduces to closures in many cases, eliminating the need for interface definitions and implementing classes. State machines gain compile-time guarantees through the typestate pattern, catching invalid transitions before the program runs. Iterators are a first-class language feature rather than a design pattern to implement, with the standard library providing rich composition capabilities. Command and Observer translate with minor adjustments to accommodate ownership, often becoming cleaner in the process. The visitor pattern, controversial in any language, finds limited use in Rust where pattern matching often serves better.
The patterns in this chapter share a common theme: behavior distribution. How do objects coordinate? How do algorithms vary independently from the objects they process? How do state changes propagate? OOP answers these questions with interfaces and polymorphism. Rust provides the same answers but adds ownership awareness that prevents many runtime errors. This chapter examines each pattern, showing both the mechanical translation and the idiomatic alternatives that Rust enables.
Strategy via trait objects or closures
The Strategy pattern defines a family of algorithms, encapsulates each one, and makes them interchangeable. Clients select an algorithm at runtime without coupling to its implementation. In OOP, this typically involves an interface with an execute method and multiple implementing classes. The pattern decouples algorithm selection from algorithm use, enabling runtime flexibility without conditional logic scattered throughout the codebase.
The motivation for Strategy appears whenever behavior must vary based on context. A payment system processes credit cards differently from bank transfers. A compression library might offer multiple algorithms with different speed and size trade-offs. A game might apply different AI strategies to different difficulty levels. Without Strategy, these variations become if-else chains or switch statements, growing unwieldy as options multiply.
Rust offers two primary approaches: trait objects for complex strategies with multiple methods, and closures for single-method strategies. The choice depends on how much state and behavior the strategy carries. When a strategy is a single function with no persistent state, closures provide elegant simplicity. When strategies have multiple methods, associated data, or complex initialization, traits offer the necessary structure. Understanding when to use each approach is key to idiomatic Rust design.
Consider a payment processing system that supports multiple payment methods:
pub trait PaymentStrategy { fn process(&self, amount: f64) -> Result<String, PaymentError>; fn refund(&self, transaction_id: &str) -> Result<(), PaymentError>;}
pub struct CreditCardPayment { card_number: String, expiry: String,}
impl PaymentStrategy for CreditCardPayment { fn process(&self, amount: f64) -> Result<String, PaymentError> { // Process credit card payment Ok(format!("cc-txn-{}", uuid::Uuid::new_v4())) }
fn refund(&self, transaction_id: &str) -> Result<(), PaymentError> { // Process refund Ok(()) }}
pub struct PayPalPayment { email: String,}
impl PaymentStrategy for PayPalPayment { fn process(&self, amount: f64) -> Result<String, PaymentError> { // Process PayPal payment Ok(format!("pp-txn-{}", uuid::Uuid::new_v4())) }
fn refund(&self, transaction_id: &str) -> Result<(), PaymentError> { Ok(()) }}
pub struct Checkout { payment: Box<dyn PaymentStrategy>,}
impl Checkout { pub fn new(payment: Box<dyn PaymentStrategy>) -> Self { Checkout { payment } }
pub fn process_order(&self, amount: f64) -> Result<String, PaymentError> { self.payment.process(amount) }}The Checkout struct holds a Box<dyn PaymentStrategy>, enabling runtime selection of payment methods. Clients construct the appropriate payment type, box it, and pass it to Checkout. The checkout delegates to whatever strategy it holds without knowing the concrete type. This is the heart of Strategy: the client code (Checkout) operates through the trait interface, remaining ignorant of and independent from the concrete strategies.
The Box<dyn PaymentStrategy> enables runtime strategy selection. The box provides heap allocation and dynamic dispatch, necessary because different payment types have different sizes and implementations. Changing strategy at runtime means replacing the boxed trait object, perhaps based on user selection or configuration.
When strategies have a single method, closures provide a lighter-weight alternative. A sorting function can accept a generic comparison function F: Fn(&T, &T) -> Ordering and delegate to sort_by. Callers provide the strategy inline: |a, b| a.cmp(b) for ascending, |a, b| b.cmp(a) for descending, or any custom logic. The closure captures context from its environment, serving as a single-method strategy without defining separate types. This approach pervades Rust’s standard library. Methods like filter, map, find, and sort_by all accept closures as strategies.
For strategies that need to be stored and called multiple times, Box<dyn Fn> provides the necessary indirection:
pub struct PriceCalculator { discount_strategy: Box<dyn Fn(f64) -> f64>,}
impl PriceCalculator { pub fn new(discount_strategy: Box<dyn Fn(f64) -> f64>) -> Self { PriceCalculator { discount_strategy } }
pub fn calculate(&self, base_price: f64) -> f64 { (self.discount_strategy)(base_price) }}// Different discount strategies as closureslet no_discount = PriceCalculator::new(Box::new(|price| price));let ten_percent_off = PriceCalculator::new(Box::new(|price| price * 0.9));let fixed_discount = PriceCalculator::new(Box::new(move |price| price - 5.0));
// Member discount capturing external statelet member_discount_rate = 0.15;let member_discount = PriceCalculator::new( Box::new(move |price| price * (1.0 - member_discount_rate)));The move keyword captures values by ownership when closures outlive their creation scope.
The choice between trait objects and closures depends on strategy complexity. Traits suit strategies with multiple methods, associated types, or complex state. A payment processor needing both process and refund methods benefits from a trait. A validation strategy needing configuration data benefits from a struct implementing the strategy trait. Closures suit simple transformations and algorithms where a single function suffices. A comparison function for sorting, a predicate for filtering, a transformation for mapping: all fit naturally as closures.
The practical effect is that Strategy in Rust often disappears into language features. Where OOP requires defining an interface, creating implementing classes, and wiring them together, Rust accepts a closure inline. The pattern’s intent (interchangeable algorithms) remains; the ceremony vanishes.
This simplification reflects a broader truth about design patterns in Rust. Many patterns exist to work around language limitations. When the language provides better primitives, the pattern dissolves. Strategy dissolved into first-class functions and closures. Singleton dissolved into static items with lazy initialization. Null Object dissolved into Option with its None variant. Recognizing when a pattern has dissolved helps avoid over-engineering solutions that Rust already provides at the language level.
Observer and event systems
The Observer pattern establishes a one-to-many dependency between objects. When a subject changes state, all registered observers receive notification. This pattern enables loose coupling between components that need to react to events without tight integration. A stock price ticker notifies multiple displays when prices change. A user interface component notifies validators when input changes. A sensor system notifies loggers, alerts, and dashboards when readings arrive.
The power of Observer lies in its decoupling. The subject knows nothing about what observers do with notifications; it declares “something happened” and lets interested parties respond. Observers know nothing about each other; each reacts independently without coordination. Adding or removing observers requires no changes to the subject or other observers. This loose coupling enables modular designs where concerns separate cleanly.
In OOP languages, observers typically implement an interface with an update method, and subjects maintain a list of observer references. Registration and notification are straightforward: observers call a subscribe method, subjects iterate through the list calling update on each. The pattern works well until questions of lifetime and identity arise. How do observers unsubscribe? How does the subject handle an observer that no longer exists? How do observers handle subjects that disappear?
Rust’s ownership rules complicate this pattern because observers and subjects would naturally want references to each other, creating potential borrowing conflicts. If the subject holds references to observers, and observers hold references to the subject (to unsubscribe, perhaps), circular references emerge. Rust’s borrow checker prohibits such structures without runtime indirection.
This constraint, initially frustrating, often leads to cleaner designs that separate concerns more rigorously. When forced to think about who owns what, developers often discover that the bidirectional references are unnecessary. An observer that receives notifications usually does not need to know about the subject; it reacts to events, period. An unsubscribe mechanism can use handles rather than self-references. The borrow checker’s restrictions push toward designs that would be considered best practice in any language.
A straightforward approach uses trait objects with careful lifetime management:
pub trait Observer { fn on_event(&self, event: &str);}
pub struct EventEmitter { observers: Vec<Box<dyn Observer>>,}
impl EventEmitter { pub fn new() -> Self { EventEmitter { observers: Vec::new() } }
pub fn subscribe(&mut self, observer: Box<dyn Observer>) { self.observers.push(observer); }
pub fn emit(&self, event: &str) { for observer in &self.observers { observer.on_event(event); } }}
pub struct Logger;
impl Observer for Logger { fn on_event(&self, event: &str) { println!("[LOG] {}", event); }}This design transfers ownership of observers to the emitter, preventing modification after subscription without interior mutability.
For scenarios requiring observer removal or modification, a handle-based system provides more flexibility:
use std::collections::HashMap;
pub type ObserverId = u64;
pub struct EventBus { next_id: ObserverId, observers: HashMap<ObserverId, Box<dyn Fn(&str)>>,}
impl EventBus { pub fn new() -> Self { EventBus { next_id: 0, observers: HashMap::new(), } }
pub fn subscribe<F: Fn(&str) + 'static>(&mut self, callback: F) -> ObserverId { let id = self.next_id; self.next_id += 1; self.observers.insert(id, Box::new(callback)); id }
pub fn unsubscribe(&mut self, id: ObserverId) -> bool { self.observers.remove(&id).is_some() }
pub fn emit(&self, event: &str) { for callback in self.observers.values() { callback(event); } }}
// Usagelet mut bus = EventBus::new();let id = bus.subscribe(|event| println!("Received: {}", event));bus.emit("user_logged_in");bus.unsubscribe(id);Closures serve as observers, capturing any context they need. This pattern aligns well with Rust idioms while providing the decoupling that Observer intends.
For type-safe events, generics and enums can replace string-based event identification:
pub enum AppEvent { UserLoggedIn { user_id: u64, username: String }, ItemPurchased { item_id: u64, price: f64 }, ErrorOccurred { code: i32, message: String },}
pub struct TypedEventBus { handlers: Vec<Box<dyn Fn(&AppEvent)>>,}
impl TypedEventBus { pub fn new() -> Self { TypedEventBus { handlers: Vec::new() } }
pub fn subscribe<F: Fn(&AppEvent) + 'static>(&mut self, handler: F) { self.handlers.push(Box::new(handler)); }
pub fn emit(&self, event: &AppEvent) { for handler in &self.handlers { handler(event); } }}
// Usage with pattern matchinglet mut bus = TypedEventBus::new();bus.subscribe(|event| { match event { AppEvent::UserLoggedIn { username, .. } => { println!("Welcome, {}!", username); } AppEvent::ItemPurchased { price, .. } => { println!("Thank you for your ${:.2} purchase!", price); } AppEvent::ErrorOccurred { message, .. } => { eprintln!("Error: {}", message); } }});The compiler ensures exhaustive handling when new event variants are added.
For concurrent applications, Arc and synchronization primitives enable thread-safe event systems. Wrapping observers in Arc<Mutex<...>> allows safe sharing across threads, though this introduces locking overhead. The tokio and async-std ecosystems provide channel-based patterns that often replace traditional observer implementations in asynchronous code. Channels offer natural thread-safety without explicit locking, and their async variants integrate smoothly with Rust’s async/await syntax.
The channel-based approach deserves particular attention. Rather than the subject notifying observers directly, the subject sends messages to a channel. Observers receive from the channel. This inversion eliminates the bidirectional reference problem entirely: the subject owns the sender, observers own receivers, and neither references the other. The channel mediates all communication. This pattern scales well to distributed systems, where the channel might be a network connection rather than an in-process queue.
State machines with enums (typestate pattern)
The State pattern allows an object to alter its behavior when its internal state changes. In OOP, this involves a state interface with different implementing classes, and the context object delegates to the current state. State transitions involve replacing the state object. The pattern centralizes state-dependent behavior, avoiding scattered conditionals that check “if in state X, do this; if in state Y, do that.”
State machines appear throughout software: network connections transition through connecting, connected, and disconnected states; orders progress from pending through processing to shipped; documents move from draft through review to published. Each state permits certain operations and forbids others. A shipped order cannot be modified; a disconnected socket cannot send data; a published document cannot return to draft. These constraints represent business logic that, when violated, causes bugs.
The OOP State pattern catches violations at runtime: calling an invalid method returns an error or throws an exception. The program compiles successfully even if the logic is wrong. Rust offers a powerful alternative: the typestate pattern, which encodes state in the type system. Invalid transitions become compile errors rather than runtime errors. The program cannot be compiled if it attempts an impossible state transition.
This compile-time guarantee comes from using distinct types for each state rather than a single type with a state field. A Draft type and an Approved type are fundamentally different, not variations of the same type. Methods available on Draft (like edit and submit) differ from methods available on Approved (like publish). Attempting to call edit on an Approved document produces a compile error because Approved has no such method.
The power of this approach becomes apparent in complex protocols. A network connection with states Disconnected, Connecting, Connected, and Closing might have dozens of operations, each valid only in certain states. Encoding this as a single type with state field requires runtime checks everywhere. Encoding it as typestate means methods only exist where they make sense. The API surface itself documents valid operations.
Rust can implement the traditional approach, but enums and the typestate pattern often provide superior alternatives that catch invalid transitions at compile time. The traditional approach remains useful for comparison and for situations where runtime flexibility outweighs compile-time safety.
A traditional trait-based state machine might model a document workflow. A DocumentState trait declares methods for each possible action: edit, submit, approve, reject, and a query can_edit. The Draft struct implements this trait, transitioning to PendingReview on submit and returning itself unchanged on approve or reject (which make no sense in draft state).
This works but has a problem: invalid transitions compile successfully and fail silently at runtime. Calling approve on a draft returns the same draft, hiding the logical error. Such a design includes approve and reject methods on Draft that do nothing meaningful, yet they must exist because the trait requires them. Every state must handle every possible action, even when the action makes no sense for that state. This leads to defensive coding that obscures intent and permits bugs.
The typestate pattern uses distinct types for each state, making invalid transitions uncompilable. The state carries data appropriate to that state, and methods exist only on states where they make sense. Rather than one type with a state field, each state becomes its own type. Methods that transition between states consume the old type and return the new one, preventing use of the old state after transition. The type system becomes the state machine, and the compiler becomes its enforcer.
pub struct Draft { content: String,}
pub struct PendingReview { content: String,}
pub struct Approved { content: String, approved_by: String,}
pub struct Rejected { content: String, reason: String,}
impl Draft { pub fn new() -> Self { Draft { content: String::new() } }
pub fn edit(mut self, content: &str) -> Self { self.content = content.to_string(); self }
pub fn submit(self) -> PendingReview { PendingReview { content: self.content } }}
impl PendingReview { pub fn approve(self, approver: &str) -> Approved { Approved { content: self.content, approved_by: approver.to_string(), } }
pub fn reject(self, reason: &str) -> Rejected { Rejected { content: self.content, reason: reason.to_string(), } }}
impl Approved { pub fn content(&self) -> &str { &self.content }}Methods consume self and return the new state type. A Draft can only transition to PendingReview. A PendingReview can only become Approved or Rejected. Attempting to call approve on a Draft produces a compile error because Draft has no such method.
This is not a runtime check or an error return; the code cannot be written in the first place.
Each state struct carries only the data relevant to that state. A Draft needs content. A PendingReview needs content plus perhaps reviewer information. An Approved needs content plus approver and approval timestamp. A Rejected needs content plus rejection reason. The state type captures not only what operations are valid but what data is available.
The consumption of self deserves attention. Each transition method takes ownership of the current state and returns a new state. After calling draft.submit(), the variable draft can no longer be used. The value has moved into the transition method and no longer exists. This move semantics prevents accidental use of stale state, a category of bug that runtime state machines must guard against manually.
The trade-off is that compile-time state machines work best when the state is known at compile time. Code that stores documents in a collection, where each document might be in a different state, cannot directly use typestate. The type system needs a single type to store, not a family of related types. For such scenarios, an enum wrapper provides the necessary uniformity while preserving the internal guarantees.
The state transitions form a clear diagram:
graph TD
S(( )) -- "new()" --> D["Draft"]
D -- "submit()" --> P["PendingReview"]
P -- "approve()" --> A["Approved"]
P -- "reject()" --> R["Rejected"]
R -- "edit()" --> D
A --> E(((" ")))
R --> E
[!visual-conversion] Valid state transitions enforced at compile time through distinct types. Print UML state diagram (PDF 407, printed p. 399) recreated in Mermaid; start dot and end bullseye drawn as empty circles. The print’s
edit()arrow runs from Rejected back to Draft (the listing above has no such method onRejected; transcribed as printed).
When code needs to hold documents in any state, an enum wraps the possibilities:
pub enum Document { Draft(Draft), PendingReview(PendingReview), Approved(Approved), Rejected(Rejected),}
impl Document { pub fn try_submit(self) -> Self { match self { Document::Draft(d) => Document::PendingReview(d.submit()), other => other, // No transition for other states } }}The enum approach enables runtime state checks while the typestate pattern provides compile-time guarantees. Both have their place: typestate for APIs where invalid transitions should be impossible, enums for storage and dynamic dispatch scenarios.
Choosing between them depends on how the state machine is used. An API for building a request might use typestate: you cannot send a request until you have set the URL, and once sent, you cannot modify it. The compiler enforces this. A workflow engine storing documents in various states needs a single Document type for its collection, making an enum appropriate. Sometimes both coexist: typestate for the API surface, enum for internal storage.
The typestate pattern extends beyond state machines. Builder patterns use it to ensure required fields are set. Connection handles use it to distinguish connected from disconnected states. File handles use it to track whether a file is open for reading, writing, or closed. Anywhere that compile-time enforcement of protocol or lifecycle matters, typestate provides guarantees that runtime checks cannot match.
The builder pattern variation deserves special mention. A builder with
typestate can require certain fields in any order while preventing build
until all are set. Builder<NoUrl> has a url method returning
Builder<HasUrl>. Only Builder<HasUrl> has a build method.
This prevents constructing incomplete requests without runtime
checks, a common source of bugs in OOP builders that rely on runtime
validation.
Command pattern
The Command pattern encapsulates a request as an object, allowing parameterization, queuing, logging, and undo operations. Each command knows how to execute its action. A command processor executes commands without knowing their specifics. The pattern separates the issuer of a request from the object that performs it, enabling sophisticated control flows.
Command appears wherever requests must be treated as first-class objects. A text editor queues commands for undo/redo functionality. A job scheduler stores commands for later execution. A macro recorder captures commands for playback. A transaction log persists commands for recovery. In each case, the command carries all information needed to perform (and often reverse) its action.
The undo requirement shapes Command’s design more than any other factor. Without undo, commands are fire-and-forget closures. With undo, commands must store enough information to reverse their effects. An InsertText command stores position and text; undoing removes that text from that position. A Delete command must store the deleted text (not just the range) so undo can restore it. The need for reversibility drives commands toward data richness and trait-based structure.
The pattern involves several roles: the command interface declaring execute (and optionally undo), concrete commands implementing specific operations, a receiver that performs the actual work, and an invoker that triggers commands. In OOP, these typically become separate classes with specific relationships. In Rust, the same roles exist but may be implemented with less ceremony.
Rust’s ownership model intersects with Command in interesting ways. Commands that modify state need access to that state, but storing a reference in the command creates lifetime complexity. Several approaches address this: commands can hold all necessary data without external references, commands can receive the target as a parameter to execute, or commands can use interior mutability patterns. The right choice depends on the specific requirements.
The closure approach works beautifully for simple command queues
without undo requirements. A queue of Box<dyn FnOnce()>
captures both the operation and its context, executing each closure in
sequence. This fits scenarios like task queues, deferred execution, and
one-shot callbacks. The closure encapsulates everything: the
operation, its parameters, and any captured environment. No separate
command types needed.
When commands must support undo, the design becomes more structured. Each command needs both execute and undo methods, requiring a trait rather than a simple closure. The command must store enough information to reverse its operation, which varies by command type. Insert stores position and text. Delete stores position, length, and the deleted content. Move stores old and new positions. The command becomes a data structure, not just a function.
In Rust, commands can be trait objects, enums, or closures depending on requirements. For simple command queues, closures suffice:
pub struct CommandQueue { commands: Vec<Box<dyn FnOnce()>>,}
impl CommandQueue { pub fn new() -> Self { CommandQueue { commands: Vec::new() } }
pub fn add<F: FnOnce() + 'static>(&mut self, command: F) { self.commands.push(Box::new(command)); } pub fn execute_all(self) { for command in self.commands { command(); } }}The FnOnce trait allows commands that consume captured values. Each command runs exactly once when the queue executes. This suits fire-and-forget scenarios where commands execute in order and then disappear.
For undo functionality, commands need execute and undo methods, making a trait appropriate. An initial approach might have commands hold references or pointers to the objects they modify, but this creates lifetime and safety challenges. A command holding a pointer to a text editor must ensure that pointer remains valid throughout the command’s lifetime, leading to either unsafe code or complex reference management.
A safer design passes the target as a parameter to execute and undo, separating the command’s data from the object it modifies. The command stores what to do (insert text at position 5), not where to do it (this specific editor). The invoker provides the target when executing, maintaining clear ownership.
This separation has subtle benefits. Commands become pure descriptions of operations, independent of any particular target. The same InsertText command could apply to different editors, enabling scenarios like testing against mock editors, replaying commands on multiple targets, or serializing commands for network transmission. The command knows the operation; the invoker knows the context.
trait Command { fn execute(&self, editor: &mut TextEditor); fn undo(&self, editor: &mut TextEditor);}
pub struct InsertText { position: usize, text: String,}
impl Command for InsertText { fn execute(&self, editor: &mut TextEditor) { editor.content.insert_str(self.position, &self.text); }
fn undo(&self, editor: &mut TextEditor) { let end = self.position + self.text.len(); editor.content.drain(self.position..end); }}
pub struct CommandHistory { executed: Vec<Box<dyn Command>>,}
impl CommandHistory { pub fn execute(&mut self, command: Box<dyn Command>, editor: &mut TextEditor) { command.execute(editor); self.executed.push(command); }
pub fn undo(&mut self, editor: &mut TextEditor) { if let Some(command) = self.executed.pop() { command.undo(editor); } }}Commands store the data needed to execute and reverse their action. An InsertText command stores the position and text to insert; undoing means removing those characters from that position. The command history maintains executed commands as trait objects, enabling undo by popping the most recent command and calling its undo method with the editor.
This design cleanly separates concerns. Commands know what to do and how to undo it. The history knows the order of operations. The editor knows nothing about commands or history; it receives method calls and modifies its content. Each piece has a single responsibility, making the system easier to test and extend.
For closed sets of commands, enums provide pattern matching benefits. When all possible commands are known at compile time, an enum with variants for each command type offers exhaustive checking and avoids the overhead of trait objects. The match expression ensures every command type handles both execute and undo:
pub enum EditorCommand { Insert { position: usize, text: String }, Delete { position: usize, length: usize, deleted: String }, Replace { position: usize, old: String, new: String },}
impl EditorCommand { pub fn execute(&self, content: &mut String) { match self { EditorCommand::Insert { position, text } => { content.insert_str(*position, text); } EditorCommand::Delete { position, length, .. } => { content.drain(*position..*position + *length); } EditorCommand::Replace { position, old, new } => { content.drain(*position..*position + old.len()); content.insert_str(*position, new); } } }
pub fn undo(&self, content: &mut String) { match self { EditorCommand::Insert { position, text } => { content.drain(*position..*position + text.len()); } EditorCommand::Delete { position, deleted, .. } => { content.insert_str(*position, deleted); } EditorCommand::Replace { position, old, new } => { content.drain(*position..*position + new.len()); content.insert_str(*position, old); } } }}The enum ensures all command variants handle both execute and undo. Adding a new command variant forces updates to both match arms. This exhaustiveness checking is a significant advantage over trait-based commands when the trait supplies default implementations: a command type that forgets to override a default undo silently inherits the wrong behavior, a bug that surfaces only at runtime rather than as a compile error.
The Command pattern in Rust benefits from the language’s emphasis on explicit data flow. Commands store their data (what to do), receive their target (where to do it) as a parameter, and return results explicitly. No hidden state or implicit context. This explicitness makes commands easy to serialize for persistence or networking, easy to test in isolation, and easy to reason about when debugging.
Iterator as a first-class pattern
The Iterator pattern provides sequential access to elements without exposing underlying representation. Collections differ wildly in structure: arrays store elements contiguously, linked lists chain nodes through pointers, trees branch hierarchically, hash maps scatter entries across buckets. Yet code that processes elements often cares nothing for these details. It wants to visit each element in turn, apply some operation, and move on.
In most OOP languages, this requires implementing an iterator interface with hasNext and next methods. The two-method design reflects a common question: “Is there more?” followed by “Give me the next one.” This separation creates potential for misuse. Calling next without checking hasNext may return null or throw. Checking hasNext multiple times between next calls can produce surprising behavior with mutable collections.
Rust’s Iterator trait combines both queries into a single method returning Option. When next returns Some(element), there was an element and here it is. When next returns None, iteration is complete. This design eliminates the possibility of calling next without checking, because the check and retrieval are the same operation. The iterator’s state is always consistent.
Beyond safety, Rust elevates Iterator from a design pattern to a language feature. The trait provides dozens of adapter methods through default implementations. A type implementing just the next method automatically gains map, filter, take, skip, enumerate, collect, and many more. These compose into processing pipelines that express complex transformations concisely. The lazy evaluation of iterator adapters means no intermediate collections are created, processing each element through the entire pipeline before moving to the next.
The Iterator trait requires implementing a single method: next,
which returns Option<Self::Item>. The associated type Item
specifies what the iterator yields. Each call to next returns
Some (item) while elements remain and None when exhausted. This
design eliminates the two-method dance of hasNext/next, reducing
potential for misuse.
Implementing Iterator for custom types requires only defining next:
pub struct Counter { current: usize, max: usize,}
impl Counter { pub fn new(max: usize) -> Self { Counter { current: 0, max } }}
impl Iterator for Counter { type Item = usize;
fn next(&mut self) -> Option<Self::Item> { if self.current < self.max { let value = self.current; self.current += 1; Some(value) } else { None } }}
// Usage with iterator adapterslet sum: usize = Counter::new(10) .filter(|n| n % 2 == 0) .map(|n| n * n) .sum();This minimal implementation unlocks the full power of iterator adapters.
The contract is straightforward: next should return the next element if one exists, None if not. Once it returns None, it may be called again, though the standard library iterators typically continue returning None. For finite collections, the iterator tracks progress through internal state. For infinite iterators (like counting forever), next never returns None unless consumed through take or similar limiting adapters.
Once a type implements Iterator, it gains access to dozens of adapter methods through default implementations: map, filter, take, skip, enumerate, collect, and many more. These compose into processing pipelines. A counter filtering for even numbers, mapping to squares, and summing reads as a chain: Counter::new(10).filter(|n| n % 2 == 0).map(|n| n * n).sum(). Each adapter wraps the previous iterator, building a chain that processes elements on demand.
Iterators are lazy: the filter and map create wrapper iterators that do nothing until consumed. Only when sum pulls elements through the chain does any work occur. Each element passes through filter, then map, then into the sum, without intermediate collections. This efficiency comes automatically from the iterator abstraction.
This laziness has practical implications. An iterator chain with take(10) processes only ten elements, regardless of the source’s size. Chaining filter before map avoids mapping elements that will be discarded. Infinite iterators become practical because consumption
determines how many elements to process. The caller controls the
work, not the data source.
For complex data structures, implementing iteration requires consideration of borrowing. A tree structure might offer multiple iteration orders: pre-order, post-order, level-order. Each order requires its own iterator type maintaining appropriate traversal state:
pub struct TreeNode<T> { pub value: T, pub children: Vec<TreeNode<T>>,}
pub struct PreOrderIter<'a, T> { stack: Vec<&'a TreeNode<T>>,}
impl<'a, T> PreOrderIter<'a, T> { pub fn new(root: &'a TreeNode<T>) -> Self { PreOrderIter { stack: vec![root] } }}
impl<'a, T> Iterator for PreOrderIter<'a, T> { type Item = &'a T;
fn next(&mut self) -> Option<Self::Item> { self.stack.pop().map(|node| { // Push children in reverse order for left-to-right traversal for child in node.children.iter().rev() { self.stack.push(child); } &node.value }) }}impl<T> TreeNode<T> { pub fn iter(&self) -> PreOrderIter<'_, T> { PreOrderIter::new(self) }}
// Usagelet tree = TreeNode { value: 1, children: vec![ TreeNode { value: 2, children: vec![] }, TreeNode { value: 3, children: vec![] }, ],};
for value in tree.iter() { println!("{}", value);}The lifetime parameter on the iterator ties it to the tree it traverses, preventing use-after-free.
The distinction between borrowing and owning iteration becomes important for complex structures. A borrowing iterator (&tree) yields references to elements, allowing the tree to remain intact after iteration. An owning iterator (tree.into_iter()) consumes the tree, yielding owned elements. Mutable iteration (&mut tree) yields mutable references, allowing in-place modification. Each has its use case, and Rust collections typically implement all three.
Implementing iteration for custom types forces consideration of these ownership modes. Does the iterator borrow from the collection, requiring a lifetime parameter? Does it consume the collection, taking ownership of elements? Does it clone elements, providing independent copies? These decisions affect how the iterator can be used and what happens to the underlying data structure during and after iteration.
The iter, iter_mut, and into_iter naming convention that Rust collections follow provides consistency across types. Users learn to expect these three methods with predictable behavior. Custom types benefit from following this convention, making their iteration interface familiar to Rust developers.
The lifetime parameter on the iterator ties it to the tree it traverses, preventing use-after-free. The iterator yields references to values, allowing traversal without ownership transfer. When the tree goes out of scope, all iterators borrowing from it become invalid, and the compiler enforces this.
The IntoIterator trait enables types to be used in for loops directly. Implementing into_iter allows for value in tree { … } syntax, consuming the tree and yielding owned values. The distinction between Iterator (already an iterator) and IntoIterator (can become an iterator) matters: references to collections typically implement IntoIterator to yield references, while owned collections implement it to yield owned values.
Rust collections typically implement IntoIterator three ways: once
for the owned collection (Vec<T>), once for shared references
(&Vec<T>), and once for mutable references (&mut Vec<T>). This
allows idiomatic patterns like for item in &vec for borrowing
iteration and for item in vec for consuming iteration. The for loop
desugars to a call to into_iter(), which the trait implementations
direct to the appropriate iterator type.
The iterator ecosystem in Rust extends far beyond basic sequences. The itertools crate provides additional adapters for grouping, merging, and combinatorial operations. Parallel iterators from rayon enable multi-threaded processing with minimal code changes. Async streams extend the iterator concept to asynchronous contexts. The core Iterator trait serves as the foundation for this rich ecosystem.
Visitor: when and how
The Visitor pattern separates algorithms from the object structure on which they operate. New operations can be added without modifying the classes of the elements. This addresses a fundamental tension in extensibility: adding new types is easy in OOP (define a new class), but adding new operations requires modifying every existing class to add the new method. Visitor inverts this trade-off, making operations easy to add at the cost of making types harder to add.
The classic example involves an abstract syntax tree. An expression tree with Number, Add, Multiply, and Negate nodes might need evaluation, pretty-printing, optimization, and compilation operations. Without Visitor, each node class implements all operations. Adding a new operation means touching every node class. With Visitor, each operation becomes a visitor class that knows how to handle each node type. Adding a new operation means adding a new visitor without modifying existing nodes.
In OOP, this requires double dispatch: each element class implements an accept method that calls back to the visitor with this, and each visitor implements a method for each element type. First dispatch goes through the element to accept. Second dispatch goes through the visitor to the type-specific method. The dance seems awkward, and it is, but it achieves operation extensibility that OOP otherwise struggles to provide.
The boilerplate Visitor requires in OOP often discourages its use. Each element needs an accept method. Each visitor needs a method for every element type. Adding a new element type requires updating every visitor. The pattern trades one kind of change cost for another, making it suitable only when operations change more frequently than types.
Rust’s pattern matching often eliminates the need for Visitor. When elements form a closed set (an enum), adding operations means adding functions that match on the enum. This is precisely what Visitor achieves in OOP, but without the ceremony of accept methods and visitor interfaces. The enum already provides the type discrimination that Visitor’s double dispatch achieves.
An expression enum with Number, Add, Multiply, and Negate variants can support any number of operations through standalone functions:
pub enum Expr { Number(f64), Add(Box<Expr>, Box<Expr>), Multiply(Box<Expr>, Box<Expr>), Negate(Box<Expr>),}
pub fn evaluate(expr: &Expr) -> f64 { match expr { Expr::Number(n) => *n, Expr::Add(left, right) => evaluate(left) + evaluate(right), Expr::Multiply(left, right) => evaluate(left) * evaluate(right), Expr::Negate(inner) => -evaluate(inner), }}
pub fn to_string(expr: &Expr) -> String { match expr { Expr::Number(n) => n.to_string(), Expr::Add(left, right) => { format!("({} + {})", to_string(left), to_string(right)) } Expr::Multiply(left, right) => { format!("({} * {})", to_string(left), to_string(right)) } Expr::Negate(inner) => format!("(-{})", to_string(inner)), }}
pub fn count_nodes(expr: &Expr) -> usize { match expr { Expr::Number(_) => 1, Expr::Add(left, right) | Expr::Multiply(left, right) => { 1 + count_nodes(left) + count_nodes(right) } Expr::Negate(inner) => 1 + count_nodes(inner), }}Adding count_nodes or optimize means adding more functions that match on the enum. None of these changes require modifying the enum definition.
The match expressions handle each variant explicitly, and the compiler flags incomplete matches when variants change. Adding a new expression variant (say, Divide) causes every match expression to report an error until updated. This exhaustiveness checking provides the same safety guarantee that Visitor’s structure enforces in OOP.
The traditional Visitor pattern becomes relevant when the element types cannot be enumerated (they are defined by external code) or when double dispatch is genuinely needed:
trait ExprVisitor<T> { fn visit_number(&mut self, value: f64) -> T; fn visit_add(&mut self, left: T, right: T) -> T; fn visit_multiply(&mut self, left: T, right: T) -> T; fn visit_negate(&mut self, inner: T) -> T;}
impl Expr { pub fn accept<T, V: ExprVisitor<T>>(&self, visitor: &mut V) -> T { match self { Expr::Number(n) => visitor.visit_number(*n), Expr::Add(left, right) => { let l = left.accept(visitor); let r = right.accept(visitor); visitor.visit_add(l, r) } Expr::Multiply(left, right) => { let l = left.accept(visitor); let r = right.accept(visitor); visitor.visit_multiply(l, r) } Expr::Negate(inner) => { let i = inner.accept(visitor); visitor.visit_negate(i) } } }}
pub struct Evaluator;
impl ExprVisitor<f64> for Evaluator { fn visit_number(&mut self, value: f64) -> f64 { value } fn visit_add(&mut self, left: f64, right: f64) -> f64 { left + right } fn visit_multiply(&mut self, left: f64, right: f64) -> f64 { left * right } fn visit_negate(&mut self, inner: f64) -> f64 { -inner }}
pub struct PrettyPrinter;impl ExprVisitor<String> for PrettyPrinter { fn visit_number(&mut self, value: f64) -> String { value.to_string() } fn visit_add(&mut self, left: String, right: String) -> String { format!("({} + {})", left, right) } fn visit_multiply(&mut self, left: String, right: String) -> String { format!("({} * {})", left, right) } fn visit_negate(&mut self, inner: String) -> String { format!("-{}", inner) }}This Visitor implementation provides less benefit in Rust than in languages without sum types. The main advantage emerges when visitors need to maintain complex state across traversal or when element types are genuinely extensible. In my experience, reaching for pattern matching first leads to cleaner code in most Rust projects.
The expression problem, which Visitor addresses, takes a different shape in Rust. OOP struggles to add new operations to existing types; pattern matching on enums makes this trivial. OOP makes adding new types easy; enums require updating all match expressions. Neither is universally better; each favors different extension patterns. When a domain changes primarily through new types (plugin architectures, user-defined extensions), traits provide the necessary openness. When a domain changes primarily through new operations (compilers, interpreters, analyzers), enums provide better ergonomics.
Understanding this trade-off guides design decisions. A serialization library might define Serialize and Deserialize traits, allowing any type to participate. A compiler for a fixed language might use enums for its AST, knowing new node types are rare but new analysis passes are common. The choice ripples through the codebase, so making it consciously matters.
Behaviors Examined
Behavioral patterns manage communication and responsibility distribution between types. Where OOP relies on interfaces, abstract classes, and virtual dispatch, Rust implements these patterns through closures, traits, enums, and ownership-aware designs. The translations often simplify the traditional OOP approaches while adding safety guarantees that OOP cannot provide.
Strategy becomes closures for simple cases or trait objects for complex multi-method strategies. The closure approach is so natural in Rust that it hardly feels like a pattern at all. The standard library’s pervasive use of closures for filtering, mapping, and sorting demonstrates how seamlessly strategy selection integrates with everyday code. When strategies grow complex, trait objects provide the same runtime flexibility as OOP interfaces.
Observer patterns in Rust require careful attention to ownership. The bidirectional references that OOP observers often establish conflict with Rust’s single-owner model. Handle-based subscription with closure callbacks provides flexibility while respecting the borrow checker. For concurrent systems, channel-based patterns often replace traditional observers entirely, providing thread-safe communication without shared mutable state.
State machines gain compile-time guarantees through the typestate pattern, perhaps the most distinctly Rust approach in this chapter. Where OOP state machines catch invalid transitions at runtime, typestate catches them at compile time. Distinct types for each state make invalid transitions uncompilable. Enums provide runtime state storage when needed, with pattern matching ensuring exhaustive handling of all states.
The Command pattern uses closures for simple execution queues or traits for commands requiring undo. The choice depends on whether commands need multiple methods and complex state. Enum-based commands offer exhaustiveness checking, ensuring all command types handle both execute and undo without runtime type checks.
Iterator is a first-class language feature in Rust rather than a design pattern to implement manually. Implementing the single next method unlocks dozens of adapter methods through default implementations. The lazy evaluation model enables efficient processing pipelines that would require explicit optimization in OOP languages. Iterator chains read declaratively while executing imperatively, combining elegance with performance.
The Visitor pattern finds limited use in Rust because pattern matching on enums achieves the same separation of operations from data structure. Where OOP needs the double-dispatch dance of accept methods and visitor interfaces, Rust needs only a function with a match expression. When true Visitor is needed, trait-based implementations translate directly from OOP versions.
These patterns reveal a recurring theme: Rust’s language features often provide cleaner solutions than mechanical translations of OOP patterns. Closures replace single-method interfaces. Enums replace class hierarchies. Ownership eliminates defensive copying and lifetime confusion. The typestate pattern provides guarantees that OOP cannot express. Understanding when to use the traditional pattern and when to leverage Rust-specific idioms leads to code that is not only correct but also clear and maintainable.
The next chapter provides a translation guide, offering a comprehensive reference for converting OOP constructs and patterns to their Rust equivalents. It serves as a bridge between the detailed pattern discussions and everyday coding decisions.