Patterns from Functional Programming
local graph
Chapter 11 — Patterns from Functional Programming
Section titled “Chapter 11 — Patterns from Functional Programming”Patterns from Functional Programming
Section titled “Patterns from Functional Programming”The functional programming patterns in this chapter have deep roots in languages such as Lisp (1958), Meta Language (ML; 1973), and Haskell (1990). Functional programming concepts such as iterator chains, pattern matching, closures, and type classes are not unique to Rust but have been studied and practiced for decades. What makes these patterns especially useful in Rust is how they interact with the language’s distinct approach to systems programming.
Rust adapted these functional programming concepts thoughtfully, integrating them with zero-cost abstractions, ownership tracking, and memory safety guarantees. The result is a systems programming language where functional patterns enhance rather than constrain performance and safety. Iterator chains in Rust compile to code that is as efficient as hand-written loops. Pattern matching integrates with the borrow checker to ensure exhaustiveness and safety. Closures capture their environment using explicit ownership semantics. Type classes, modeled through Rust’s trait system, enable flexible abstractions that work across multiple types.
Unlike the previous chapter, where patterns built on each other, the patterns in this chapter are largely independent. You can apply function pipelines without using type classes, or use pattern matching without closures. Each section stands alone, though they complement each other when combined.
We’ll continue developing our Samsa pub/sub microservice from Chapter 9, Architectural Patterns, and Chapter 10, Patterns that Leverage the Type System, by applying the functional patterns that have proven their worth across thousands of Rust projects. As we explore each pattern, pay attention to the problem-solving process that led to its development. This same process of recognizing when functional approaches offer advantages is something you can apply in your own work.
The goal is not to make Rust code look like Haskell or Lisp, but rather to leverage Rust’s unique features to write code that is safe, fast, and expressive.
In this chapter, we’re going to cover the following main topics:
- Function pipelines and how Rust’s iterator chains enable elegant data transformation
- Using generics to model type classes and enhance the TypeState pattern
- Advanced pattern matching techniques for control flow and data extraction
- Closure-based patterns for creating flexible and reusable code components
Technical requirements
Section titled “Technical requirements”The source code for the exercises can be found on GitHub at https://github.com/PacktPublishing/Design-Patterns-and-Best-Practices-in-Rust. The repository is organized by chapter. The relevant exercises for this chapter are at https://github.com/PacktPublishing/Design-Patterns-and-Best-Practices-in-Rust/tree/main/ch11.
Function pipelines
Section titled “Function pipelines”Function pipelines are a fundamental concept in functional programming, dating back to the pipe operator in Unix shells (1970s) and higher-order functions in languages such as Lisp and ML. The pattern of chaining transformations (map, filter, fold) has been standard in functional languages since the 1970s. Languages such as Haskell, OCaml, and Scala have made extensive use of iterator-style pipelines for decades.
What Rust brings to this well-established pattern is zero-cost abstraction and ownership integration. Rust’s iterator chains compile to the same efficient machine code as hand-written loops, sometimes even more efficient due to compiler optimizations. The ownership system ensures that iterator pipelines respect borrowing rules, preventing data races and use-after-free bugs at compile time. This makes functional-style pipelines practical for systems programming where performance and safety are critical.
The power of this pattern lies not only in its elegance but also in its ability to outperform handwritten loops due to lazy evaluation. This challenges the notion that functional-style code requires performance sacrifices.
In our Samsa microservice, we need to process streams of subscription events by filtering out invalid ones, grouping by topic, and generating statistics. The imperative approach would use nested loops, mutable accumulators, and scattered validation logic. This leads to code that’s hard to read, modify, and test.
As an alternative, we could use a functional approach by creating a pipeline to process subscription events, built by applying domain-specific combinators.
Here’s a first try at implementing a subscription processing pipeline for our Samsa microservice. This pipeline will use filter to remove invalid events, map to extract data, and fold to aggregate results, which are the core building blocks of functional data processing.
First, we define the data structures used by the pipeline:
use std::collections::HashMap;
#[derive(Debug, Clone)]struct SubscriptionEvent { user_id: u64, topic: String, timestamp: u64, subscription_type: SubscriptionType,}
#[derive(Debug, Clone, PartialEq)]enum SubscriptionType { Subscribe, Unsubscribe, Invalid,}
struct SubscriptionStats { total_valid: usize, subscriptions_by_topic: HashMap<String, usize>,}Now let’s implement a functional pipeline to process these events:
impl SubscriptionEvent { fn is_valid(&self) -> bool { self.subscription_type != SubscriptionType::Invalid && !self.topic.is_empty() && self.user_id > 0 }
fn is_subscription(&self) -> bool { self.subscription_type == SubscriptionType::Subscribe }}fn process_subscription_events(events: Vec<SubscriptionEvent>) -> SubscriptionStats { let valid_events: Vec<_> = events .into_iter() .filter(|event| event.is_valid()) .collect();
let subscriptions_by_topic = valid_events .iter() .filter(|event| event.is_subscription()) .map(|event| &event.topic) .fold(HashMap::new(), |mut acc, topic| { *acc.entry(topic.clone()).or_insert(0) += 1; acc });
SubscriptionStats { total_valid: valid_events.len(), subscriptions_by_topic, }}This demonstrates the basic pipeline pattern: chain iterator operations (filter, map, fold) to transform data without intermediate mutable state.
This pipeline demonstrates three key iterator operations:
filter()removes elements that don’t match a predicate (invalid events)map()transforms elements (extracting just the topic)fold()accumulates results (counting topics in aHashMap)
Each operation is lazy. It doesn’t execute until we call collect() or another terminal operation. This means we only iterate through the data once, regardless of how many operations we chain.
We can create more powerful pipelines with custom domain-specific combinators:
trait SubscriptionProcessing { fn valid_subscriptions(self) -> Box<dyn Iterator<Item = SubscriptionEvent>>; fn count_by_topic(self) -> HashMap<String, usize>; fn recent_events(self, cutoff_timestamp: u64) -> Box<dyn Iterator<Item = SubscriptionEvent>>;}
impl<I> SubscriptionProcessing for Iwhere I: Iterator<Item = SubscriptionEvent> + 'static,{ fn valid_subscriptions(self) -> Box<dyn Iterator<Item = SubscriptionEvent>> { Box::new( self.filter(|event| event.is_valid()) .filter(|event| event.is_subscription()) ) }
fn count_by_topic(self) -> HashMap<String, usize> { self.fold(HashMap::new(), |mut acc, event| { *acc.entry(event.topic).or_insert(0) += 1; acc }) }
fn recent_events(self, cutoff_timestamp: u64) -> Box<dyn Iterator<Item = SubscriptionEvent>> { Box::new(self.filter(move |event| event.timestamp >= cutoff_timestamp)) }}This demonstrates the extension trait pattern. We define SubscriptionProcessing with domain-specific methods, then implement it for any Iterator<Item = SubscriptionEvent>. This adds our custom operations to any iterator producing subscription events.
The methods return boxed trait objects (Box<dyn Iterator>) because closures have unnamed types. Boxing provides a named type we can use in the return position. Let’s use these domain-specific combinators:
fn analyze_recent_subscriptions( events: Vec<SubscriptionEvent>, cutoff_timestamp: u64) -> HashMap<String, usize> { events .into_iter() .recent_events(cutoff_timestamp) .valid_subscriptions() .count_by_topic()}The usage reads like a domain-specific language: take events, keep recent ones, filter to valid subscriptions, and count by topic. Custom combinators let us write iterator pipelines that directly express business logic. This is more maintainable than generic filter and map subscriptions with complex closures.
Why create custom combinators instead of using standard filter/map? Readability and maintainability. valid_subscriptions() is self-documenting, while filter(|e| e.is_valid() && e.subscription_type == SubscriptionType::Subscribe) requires reading the closure to understand intent. Domain-specific combinators make code review easier and reduce the chance of subtle logic errors.
Function pipelines eliminate intermediate mutable state, making code easier to reason about and less prone to bugs.
Generics as type classes: revisiting TypeState
Section titled “Generics as type classes: revisiting TypeState”Type classes originated in Haskell as a solution to ad hoc polymorphism, introduced in Philip Wadler and Stephen Blott’s 1989 paper, How to Make Ad-Hoc Polymorphism Less Ad Hoc (https://dl.acm.org/doi/10.1145/75277.75283). The concept allows defining behavior that works across multiple types while maintaining type safety through parametric polymorphism with constraints. This has been a fundamental feature of Haskell’s type system for over three decades.
Rust’s trait system is explicitly inspired by type classes, though adapted for systems programming. Rust traits provide the same core capability, abstracting over behavior rather than just data, but integrating with ownership and borrowing rules. Where Haskell type classes work in a garbage-collected environment, Rust traits must respect lifetime constraints and ownership transfers. This adaptation makes type-class-style programming practical for systems code, where manual memory management and zero-cost abstractions are essential.
In this section, we’ll enhance the TypeState pattern from Chapter 10, Patterns That Leverage the Type System, using generics to create more flexible and powerful type-safe state machines, such as state type markers and a core subscription structure with generic state.
In Chapter 10, we implemented TypeState with separate impl blocks for each state. This works but has limitations: adding new states requires modifying multiple places, and we can’t write generic code that works across states with similar capabilities.
Type classes (traits with associated types) solve this by letting us define state transition capabilities that multiple states can share. A subscription that can be cancelled implements Cancellable, whether it’s Active or Suspended. This enables generic code that works with any cancellable subscription.
In this design, traits serve as type classes: Activatable, Suspendable, and Cancellable each define a capability that certain states possess. A Pending subscription implements Activatable. An Active subscription implements both Suspendable and Cancellable. This is the type class pattern. We define abstract capabilities as traits and implement them for types that have those capabilities.
Let’s start by defining a set of zero-sized marker types that represent the possible states of a subscription:
use std::marker::PhantomData;
#[derive(Debug)]struct Pending;
#[derive(Debug)]struct Active;
#[derive(Debug)]struct Suspended;
#[derive(Debug)]struct Cancelled;
#[derive(Debug)]struct Subscription<S> { id: u64, user_id: u64, topic: String, created_at: u64, _state: PhantomData<S>,}These marker types exist only at compile time to track subscription state. The Subscription<S> struct is generic over its state, meaning Subscription<Pending> and Subscription<Active> are different types even though they contain the same data fields.
The PhantomData<S> field tells the compiler about the state parameter without storing anything at runtime. This is the foundation of the TypeState pattern: state is tracked in the type system with zero runtime cost.
Now let’s define the operations available in each state using traits as type classes. Each trait represents a capability (Activatable, Suspendable, Cancellable), and we implement these traits only for states where those operations are valid. This is the type class pattern. Traits define capabilities, and implementations specify which types have those capabilities:
// Type class for subscriptions that can be activatedtrait Activatable { type Output; fn activate(self) -> Result<Self::Output, ActivationError>;}
// Type class for subscriptions that can be suspendedtrait Suspendable { type Output; fn suspend(self, reason: String) -> Self::Output;}
// Type class for subscriptions that can be cancelledtrait Cancellable { type Output; fn cancel(self, reason: String) -> Self::Output;}
#[derive(Debug)]enum ActivationError { InvalidUser, TopicNotFound,}These traits define state transitions as consuming methods that return new states. Activatable takes ownership of a pending subscription and returns either an active one or an error. Suspendable and Cancellable similarly consume subscriptions and return new states.
This approach prevents invalid transitions; for example, you cannot suspend a pending subscription because Subscription<Pending> does not implement the Suspendable trait.
Let’s implement these traits for the appropriate states. First, let’s implement the constructor for pending subscriptions:
impl Subscription<Pending> { fn new(id: u64, user_id: u64, topic: String) -> Self { Self { id, user_id, topic, created_at: std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .unwrap() .as_secs(), _state: PhantomData, } }}Now we need to be able to turn a pending subscription into something we can use. It needs to be in the active state for that. Let’s implement that state transition with TypeState:
impl Activatable for Subscription<Pending> { type Output = Subscription<Active>;
fn activate(self) -> Result<Self::Output, ActivationError> { if self.user_id == 0 { return Err(ActivationError::InvalidUser); }
if self.topic.is_empty() { return Err(ActivationError::TopicNotFound); }
Ok(Subscription { id: self.id, user_id: self.user_id, topic: self.topic, created_at: self.created_at, _state: PhantomData, }) }}The activate method validates the subscription data and returns Result<Subscription<Active>, ActivationError>. The pending subscription is consumed, so it can’t be reused. If activation succeeds, you receive an active subscription. If it fails, both the error and the consumed subscription are gone. You’d need to create a new one. This protects us from then using the invalid subscription. If it doesn’t exist, we can’t try to do anything with it by mistake.
The remaining implementations follow the same pattern: suspended subscriptions can be reactivated or cancelled, active subscriptions can be suspended or cancelled, but pending subscriptions must be activated first. The full implementations are available in the chapter’s code repository.
Now we can create generic functions that work with any type satisfying certain constraints:
fn cancel_subscription_with_audit<S>( subscription: Subscription<S>, reason: String,) -> Subscription<Cancelled>where Subscription<S>: Cancellable<Output = Subscription<Cancelled>>,{ println!("Auditing cancellation of subscription {}: {}", subscription.id, reason); subscription.cancel(reason)}SubscriptionManager keeps separate vectors for subscriptions that are in different states. This design makes state explicit at the storage level, with active subscriptions living in one vector and suspended in another.
Let’s see how state transitions work in practice (in production, this would be backed by a database, but the type separation would remain):
struct SubscriptionManager { active_subscriptions: Vec<Subscription<Active>>, suspended_subscriptions: Vec<Subscription<Suspended>>, cancelled_subscriptions: Vec<Subscription<Cancelled>>,}State transitions move subscriptions between collections. What is interesting here is that it is impossible to accidentally have an Active subscription in the Cancelled Vec, or any similar mistake. Our state collections enforce that at compile time:
impl SubscriptionManager { fn new() -> Self { Self { active_subscriptions: Vec::new(), suspended_subscriptions: Vec::new(), cancelled_subscriptions: Vec::new(), } }
fn create_subscription(&mut self, user_id: u64, topic: String) -> Result<u64, ActivationError> { let id = 1234; // rand::random(); simplified let pending = Subscription::new(id, user_id, topic); let active = pending.activate()?;
self.active_subscriptions.push(active); Ok(id) }}The create_subscription method demonstrates the TypeState flow in action. We create a Subscription<Pending>, then immediately try to activate it. If activation succeeds, we get back a Subscription<Active> that we can store. If it fails, the pending subscription is consumed and gone. We can’t accidentally use an invalid subscription.
Now let’s implement state transitions for existing subscriptions:
impl SubscriptionManager { fn suspend_subscription(&mut self, id: u64, reason: String) -> Result<(), String> { if let Some(pos) = self.active_subscriptions.iter().position(|s| s.id == id) { let subscription = self.active_subscriptions.remove(pos); // Assuming Suspendable is implemented for Subscription<Active> // let suspended = subscription.suspend(reason); // self.suspended_subscriptions.push(suspended); Ok(()) } else { Err("Subscription not found or not active".into()) } }}The suspend_subscription method shows how state transitions work with stored subscriptions. We find the subscription by ID, remove it from active_subscriptions (which gives us ownership of a Subscription<Active>), call suspend() to get a Subscription<Suspended>, and push it onto suspended_subscriptions. The types guide every step. We couldn’t accidentally push the active subscription onto the suspended vector.
Cancellation is similar, but must handle subscriptions in multiple states:
impl SubscriptionManager { fn cancel_subscription(&mut self, id: u64, reason: String) -> Result<(), String> { // Try to cancel from active subscriptions if let Some(pos) = self.active_subscriptions.iter().position(|s| s.id == id) { let subscription = self.active_subscriptions.remove(pos); // let cancelled = subscription.cancel(reason); // self.cancelled_subscriptions.push(cancelled); return Ok(()); }
// Try to cancel from suspended subscriptions if let Some(pos) = self.suspended_subscriptions.iter().position(|s| s.id == id) { let subscription = self.suspended_subscriptions.remove(pos); // let cancelled = subscription.cancel(reason); // self.cancelled_subscriptions.push(cancelled); return Ok(()); }
Err("Subscription not found".into()) }}The cancel_subscription method demonstrates that some operations apply to multiple states. Both Active and Suspended subscriptions can be cancelled because both types implement the Cancellable trait. The method tries each collection in turn, and the compiler ensures we call .cancel() only on types that support it.
Finally, let’s add a method that broadcasts to all active subscriptions with a specific topic:
impl SubscriptionManager { fn broadcast_message(&self, topic: &str, message: &str) { for subscription in &self.active_subscriptions { if subscription.topic == topic { // See the code repository for the implementation // of try_deliver_message
// try_deliver_message(subscription, message); println!("Delivering to sub {}: {}", subscription.id, message); } } }}Notice how the type system guides the implementation. When we remove a subscription from active_subscriptions, we get Subscription<Active>. When we call .suspend(reason) on it, we get back Subscription<Suspended>, which we push onto suspended_subscriptions. The compiler ensures we can’t push an active subscription onto the suspended vector because the types don’t match.
This is the power of TypeState combined with type classes. State transitions are encoded in the types, collections are typed by state, and the compiler enforces correct usage everywhere.
This approach provides precise APIs where invalid operations are impossible to express, while enabling generic code that works across multiple types with compile-time guarantees.
Pattern matching patterns
Section titled “Pattern matching patterns”Pattern matching has been a fundamental feature of functional programming languages since ML (1973). The concept allows destructuring data structures and binding variables in a single, exhaustive expression that the compiler verifies for completeness. Languages such as ML, OCaml, Haskell, Scala, and F# have made pattern matching central to their design, developing sophisticated techniques over decades of research and practice.
Rust’s pattern-matching implementation draws directly from this functional programming heritage, particularly ML and its descendants. What Rust adds is integration with the ownership system and move semantics. Patterns in Rust can move, borrow, or copy values depending on the context, and the compiler ensures that matched values respect ownership rules. Exhaustiveness checking interacts with the type system to guarantee all cases are handled, making pattern matching both safe and zero-cost.
Message routing in Samsa requires checking multiple conditions: message priority, content type, topic patterns, and payload size. With if/else chains, this logic becomes deeply nested and hard to verify for completeness. Did we handle all cases? Are any branches unreachable?
Pattern matching solves this by letting us express complex conditions declaratively while the compiler verifies exhaustiveness.
Let’s explore advanced pattern matching in our message routing system. We first define the message structures and enums that pattern matching will operate on:
#[derive(Debug, Clone)]enum Priority { Low, Normal, High, Critical,}
#[derive(Debug, Clone)]enum MessageContent { Text(String), Binary(Vec<u8>), Json(String), Empty,}
struct RichMessage { id: u64, topic: String, priority: Priority, content: MessageContent,}
#[derive(Debug, PartialEq)]enum ProcessingResult { Processed, Queued, Rejected(String), RequiresAuth(String),}Now let’s implement the routing logic using pattern matching. Pattern matching on tuples lets us check multiple conditions simultaneously. Critical messages always get immediate processing, and high-priority messages are queued or processed, depending on how much text they contain:
impl RichMessage { fn route_message(&self) -> ProcessingResult { match (&self.priority, &self.content, self.topic.as_str()) { // Critical messages always get immediate processing (Priority::Critical, _, _) => { println!("Processing critical message immediately"); ProcessingResult::Processed }
// High priority text messages to system topics (Priority::High, MessageContent::Text(text), topic) if topic.starts_with("system.") => { if text.len() > 1000 { ProcessingResult::Queued } else { ProcessingResult::Processed } }
// JSON messages to API topics require authentication (_, MessageContent::Json(_), topic) if topic.starts_with("api.") => { ProcessingResult::RequiresAuth(topic.to_string()) }
// Binary messages over 10KB get queued (_, MessageContent::Binary(data), _) if data.len() > 10240 => { ProcessingResult::Queued }
// Empty messages are rejected (_, MessageContent::Empty, _) => { ProcessingResult::Rejected("Empty content not allowed".to_string()) }
// Default case _ => ProcessingResult::Processed, } }}Different types of messages will need different handling. What is interesting is how intricate the matches can become. Guards (with the if conditions) add extra constraints to patterns, which add an even finer-grained selection to the tuple matches.
The catch-all patterns ensure exhaustiveness, handling the Empty and default cases.
This demonstrates tuple patterns, guards with if conditions, and exhaustive matching that ensures all combinations are handled safely.
We can also apply the same pattern matching techniques to implement a state machine. Pattern matching excels at implementing state machines. We can apply the techniques we’ve used already to model states and transitions explicitly.
State machines and tuple pattern matching aren’t mutually exclusive. We’re using tuple patterns to implement the state machine. The match (state, event) expression is a tuple pattern. What makes this a “state machine” is the structure: we’re explicitly modeling states and transitions, with the pattern match handling all valid combinations. This is more structured than ad hoc conditionals.
Let’s create a connection state manager:
#[derive(Debug, Clone)]enum ConnectionState { Disconnected, Connecting { attempt: u32 }, Connected { since: u64 }, Authenticated { user_id: u64, session_token: String }, Error { error_code: u32, retry_after: Option<u64> },}
#[derive(Debug)]enum ConnectionEvent { Connect, Disconnect, Authenticate(u64, String), Error(u32), Retry, Timeout,}This state machine models a connection lifecycle with five states. The Connecting state carries an attempt count. The Connected state tracks when the connection was established. The Authenticated state includes user credentials. The Error state optionally includes retry timing.
Pattern matching will let us handle all valid state transitions explicitly while catching invalid ones. The state machine takes the current state and event, returning the new state plus actions. Let’s see the core transition logic:
fn handle_connection_event( state: ConnectionState, event: ConnectionEvent) -> (ConnectionState, Vec<String>) { let mut actions = Vec::new();
let new_state = match (state, event) { // From Disconnected state (ConnectionState::Disconnected, ConnectionEvent::Connect) => { actions.push("Starting connection".to_string()); ConnectionState::Connecting { attempt: 1 } }We now have many tools in our toolbox for dealing with the different possible states, even ones that have intricate logic. For example, the Connecting state could be messy because we need to implement a retry mechanism. Traditionally, this is done with nesting or an interlocking state machine.
Here, it’s one match that tracks retry attempts with pattern variables and guards, while also defining transitions for other states:
// From Connecting state with retry logic (ConnectionState::Connecting { attempt }, ConnectionEvent::Timeout) if attempt < 3 => { actions.push(format!("Retrying connection (attempt {})", attempt + 1)); ConnectionState::Connecting { attempt: attempt + 1 } }
(ConnectionState::Connecting { attempt }, ConnectionEvent::Timeout) => { actions.push(format!("Max attempts reached ({})", attempt)); ConnectionState::Error { error_code: 1001, retry_after: Some(30) } }
(ConnectionState::Connecting { .. }, ConnectionEvent::Connect) => { actions.push("Connection established".to_string()); ConnectionState::Connected { since: current_timestamp() } }
// From Connected state (ConnectionState::Connected { .. }, ConnectionEvent::Authenticate(user_id, token)) => { actions.push(format!("User {} authenticated", user_id)); ConnectionState::Authenticated { user_id, session_token: token } }These patterns show the power of matching on tuple patterns with guards. The (ConnectionState::Connecting { attempt }, ConnectionEvent::Timeout) if attempt < 3 pattern only matches timeouts when we haven’t exceeded the retry limit. The compiler verifies we’ve handled all state/event combinations exhaustively.
Let’s see the remaining transitions:
// Error transitions from any state (_, ConnectionEvent::Error(code)) => { actions.push(format!("Error occurred: {}", code)); ConnectionState::Error { error_code: code, retry_after: if code < 2000 { Some(10) } else { None } } }
// Invalid transitions - maintain current state (current_state, _) => { actions.push("Invalid transition ignored".to_string()); current_state } };
(new_state, actions)}
fn current_timestamp() -> u64 { std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .unwrap() .as_secs()}The catch-all pattern (current_state, _) handles invalid transitions by maintaining the current state. This prevents crashes from unexpected events while logging that something unexpected occurred. The state machine is both safe and flexible. It handles valid transitions precisely while gracefully handling invalid ones.
This state machine demonstrates sophisticated pattern matching with guards, destructuring, and exhaustive coverage that ensures all possible combinations are handled correctly.
Patterns using closures
Section titled “Patterns using closures”Closures (also called lambda functions or anonymous functions) are functions that capture variables from their surrounding scope. Unlike regular functions, a closure can “remember” values that existed when it was created, carrying that state wherever it goes. This makes them powerful for callbacks, deferred execution, and creating specialized behavior at runtime.
Closures originated in Lisp in 1958, making them one of the oldest concepts in programming language design. This long history means closure patterns have been refined over decades. Functional languages have used closure-based patterns for configuration, callbacks, and higher-order functions for decades. Languages such as Scheme, Haskell, OCaml, JavaScript, and many others have developed sophisticated patterns around closures.
What makes Rust’s closure implementation unique is how it integrates with the ownership system. Rust has three closure traits: Fn, FnMut, and FnOnce. These traits explicitly encode how closures interact with captured values. The compiler automatically infers which trait a closure implements based on how it uses captured variables, ensuring memory safety without garbage collection. This allows closure-based patterns common in functional and dynamic languages to work efficiently in systems programming contexts where performance and safety are critical.
Closure traits and capture semantics
Section titled “Closure traits and capture semantics”Understanding Rust’s three closure traits helps us write better closure-based code. The Fn trait is for closures that only borrow values immutably. These closures can be called multiple times. The FnMut trait is for closures that borrow values mutably. The FnOnce trait is for closures that consume captured values and can only be called once.
Rust automatically infers which trait a closure implements based on how it uses captured variables. A closure that doesn’t modify captures implements Fn. A closure that modifies captures implements FnMut. A closure that moves captures implements FnOnce. This automatic inference means we can write natural closure syntax and trust that Rust will enforce correct usage.
The patterns we’ll explore – configurable filters, strategy implementations, and processing pipelines – demonstrate how closures enable flexible, efficient, and composable code while maintaining the safety and performance characteristics Rust is known for. Closures in Rust aren’t just convenient syntax for small functions; they’re a fundamental tool for building flexible architectures that remain performant and safe.
Configurable message filters
Section titled “Configurable message filters”Consider message filtering: we might filter by priority, by topic pattern, by timestamp, or by content size. Writing separate functions for each combination leads to an explosion of specialized code. What if we need to combine filters dynamically?
Closures solve this by packaging behavior with captured data. A filter closure can capture a timestamp threshold, a topic prefix, or any other configuration by creating reusable, composable filtering logic. Instead of writing rigid filtering logic, we can accept closures that define the filtering criteria. This makes the code flexible and reusable while maintaining type safety and performance.
Let’s start with a basic structure for message filters that uses closures:
// A simplified Message struct for the filter examplepub struct Message { pub id: u64, pub topic: String, pub timestamp: u64, // Other fields omitted for brevity}
struct MessageFilter<F> { predicate: F, name: String,}
impl<F> MessageFilter<F>where F: Fn(&Message) -> bool,{ fn new(name: String, predicate: F) -> Self { Self { predicate, name } }
fn matches(&self, message: &Message) -> bool { (self.predicate)(message) }}This structure is generic over the closure type F, constrained by the Fn(&Message) -> bool trait. This means any closure that takes a reference to a Message and returns a bool can be used as a filter. The closure is immutable (using Fn rather than FnMut), which allows the filter to be used multiple times without consuming it.
We can make filters even more powerful by allowing them to be combined. Here’s how we add a method to combine two filters with a logical AND:
impl<F> MessageFilter<F>where F: Fn(&Message) -> bool + 'static,{ fn and<G>(self, other: MessageFilter<G>) -> MessageFilter<Box<dyn Fn(&Message) -> bool>> where G: Fn(&Message) -> bool + 'static, { let combined_name = format!("{} AND {}", self.name, other.name); MessageFilter::new(combined_name, Box::new(move |msg| { self.matches(msg) && other.matches(msg) })) }}The and method creates a new filter that combines two existing filters. It uses Box<dyn Fn(&Message) -> bool> as the return type. The move keyword captures both filters by value, and the combined closure calls matches on each.
Now we can create useful filters with concise closure syntax:
/// Returns a tuple of three filters with complex impl Trait types./// The type complexity is intentional to demonstrate returning closures with different predicates.#[allow(clippy::type_complexity)]pub fn create_message_filters() -> ( MessageFilter<impl Fn(&Message) -> bool>, MessageFilter<impl Fn(&Message) -> bool>, MessageFilter<impl Fn(&Message) -> bool>,) { let large_filter = MessageFilter::new( "Large Messages".to_string(), // Simplified content check |_msg: &Message| false // msg.value.len() > 1000 );
let system_filter = MessageFilter::new( "System Topics".to_string(), |msg: &Message| msg.topic.starts_with("system.") );
let recent_filter = MessageFilter::new( "Recent Messages".to_string(), move |msg: &Message| { let now = current_timestamp(); now.saturating_sub(msg.timestamp) <= 3600 } );
(large_filter, system_filter, recent_filter)}This demonstrates three different closure patterns. The first two use simple closures that just check conditions. The third closure uses move to ensure it owns any captured values and calculates message freshness by comparing timestamps. This is particularly powerful because the closure can capture complex initialization logic while presenting a simple filtering interface.
Why closures instead of functions?
Section titled “Why closures instead of functions?”You might wonder why we use closures here instead of regular functions. The key difference is capture: closures can capture values from their environment.
Consider the “Recent Messages” filter. It needs a cutoff timestamp that’s calculated when the filter is created, not when it’s called. A regular function would need this passed as a parameter every time:
fn is_recent(msg: &Message, cutoff: u64) -> bool { msg.timestamp >= cutoff}
// Awkward: must pass cutoff everywhere// messages.filter(|msg| is_recent(msg, cutoff))With a closure, we capture the cutoff once and get a simple Fn(&Message) -> bool:
let cutoff = current_timestamp() - 3600;let is_recent = move |msg: &Message| msg.timestamp >= cutoff;// messages.filter(is_recent)Closures let us create specialized behavior at runtime while presenting a uniform interface. This is essential for composable, reusable code.
The Strategy pattern with closures
Section titled “The Strategy pattern with closures”The Strategy pattern traditionally uses interfaces or abstract classes to define interchangeable algorithms. However, defining a new struct and trait implementation for every strategy creates boilerplate, and strategies can’t easily capture runtime state without additional plumbing. In Rust, closures solve both problems. They provide a more flexible and ergonomic approach. No separate struct definitions are needed, and closures naturally capture state from their environment. Instead of defining trait implementations for each strategy, we can use closures that capture the specific behavior we need.
Let’s build a message routing system where different routing strategies can be plugged in dynamically:
// Redefine Message to include priority and id for this examplepub struct RouteMessage { pub id: u64, pub topic: String, pub priority: Priority,}
type RoutingStrategy = Box<dyn Fn(&RouteMessage) -> Vec<String> + Send + Sync>;
struct MessageRouter { strategies: Vec<RoutingStrategy>, default_targets: Vec<String>,}
impl MessageRouter { fn new() -> Self { Self { strategies: Vec::new(), default_targets: vec!["default_queue".to_string()], } }
fn add_strategy<F>(&mut self, strategy: F) where F: Fn(&RouteMessage) -> Vec<String> + Send + Sync + 'static, { self.strategies.push(Box::new(strategy)); }
fn route_message(&self, message: &RouteMessage) -> Vec<String> { for strategy in &self.strategies { let targets = strategy(message); if !targets.is_empty() { return targets; } } self.default_targets.clone() }}MessageRouter maintains a collection of routing strategies as trait objects. Each strategy is a closure that examines a message and returns a vector of destination queues. The Send + Sync bounds ensure the closures can be used safely across threads, which is crucial for a concurrent message broker.
The routing logic tries each strategy in order until one returns a non-empty result. This provides a clean, priority-based routing system where the order in which strategies are added determines their precedence.
Now we can configure the router with specific routing behaviors using closures:
fn create_routing_strategies() -> MessageRouter { let mut router = MessageRouter::new();
// Critical messages go to emergency queue router.add_strategy(|msg| { if matches!(msg.priority, Priority::Critical) { vec!["emergency_queue".to_string()] } else { vec![] } });
// System messages distributed by topic router.add_strategy(|msg| { if msg.topic.starts_with("system.") { let service = msg.topic.strip_prefix("system.").unwrap_or("unknown"); vec![format!("system_{}_queue", service)] } else { vec![] } });
// API messages load-balanced across workers router.add_strategy({ let worker_count = 4; move |msg| { if msg.topic.starts_with("api.") { let worker_id = msg.id % worker_count; vec![format!("api_worker_{}_queue", worker_id)] } else { vec![] } } });
router}Each strategy is a self-contained piece of logic. The critical message strategy checks priority. The system message strategy extracts the service name from the topic and routes accordingly. The API message strategy demonstrates closure capture – it captures worker_count and uses it for load balancing.
This approach has several advantages over traditional Strategy pattern implementations. There’s no need to define separate structs or implement traits for each strategy. Strategies can naturally capture states from their environment, and the configuration code is colocated with the router creation, making it easy to understand the routing logic at a glance.
Processing pipelines with closures
Section titled “Processing pipelines with closures”Processing pipelines are another pattern where closures shine. A pipeline is a sequence of transformations, each of which might fail. Using closures, we can build flexible, composable pipelines that handle errors gracefully.
Here’s the foundation for a generic pipeline:
type PipelineStage<T> = Box<dyn Fn(T) -> Result<T, Box<dyn std::error::Error + Send + Sync>> + Send + Sync>;
struct Pipeline<T> { stages: Vec<PipelineStage<T>>,}
impl<T> Pipeline<T>where T: Send + 'static,{ fn new() -> Self { Self { stages: Vec::new() } }
fn add_stage<F>(mut self, stage: F) -> Self where F: Fn(T) -> Result<T, Box<dyn std::error::Error + Send + Sync>> + Send + Sync + 'static, { self.stages.push(Box::new(stage)); self }
pub fn execute(&self, input: T) -> Result<T, Box<dyn std::error::Error + Send + Sync>> { self.stages.iter().try_fold(input, |acc, stage| stage(acc)) }}The Pipeline type is generic over the data being processed. It maintains a collection of processing stages, where each stage is a closure that takes a value and returns Result. The add_stage method consumes self and returns it, enabling a fluent builder-style API. The execute method runs all stages in sequence, short-circuiting on the first error.
The use of try_fold here is particularly elegant. It threads the value through all stages, stopping immediately if any stage returns Err. This is precisely the behavior we want for a processing pipeline.
The Send + Sync bounds deserve explanation. Send means the closure can be safely transferred between threads. Sync means the closure can be safely shared between threads (via references). These bounds are required because our pipeline might be used in a concurrent context. Multiple threads could execute the same pipeline simultaneously.
If your closures capture Rc or other non-thread-safe types, they won’t satisfy these bounds, and the compiler will reject them. This is Rust’s ownership system ensuring thread safety at compile time.
We can add a convenience method for validation stages:
impl<T> Pipeline<T>where T: Send + 'static,{ fn add_validation<F>(self, validator: F, error_message: String) -> Self where F: Fn(&T) -> bool + Send + Sync + 'static, { self.add_stage(move |input| { if validator(&input) { Ok(input) } else { Err(error_message.clone().into()) } }) }}The add_validation method takes a validator closure that just returns a boolean and wraps it in a stage that returns the appropriate Result. This makes it easy to add validation without writing repetitive error-handling code.
Now we can build a concrete pipeline for message processing:
// Redefining a simple message structure for the pipelinepub struct ProcessMessage { pub topic: String, pub content: MessageContent, pub metadata: HashMap<String, String>,}
fn create_message_pipeline() -> Pipeline<ProcessMessage> { Pipeline::new() .add_validation( |msg| !msg.topic.is_empty(), "Topic cannot be empty".to_string() ) .add_stage(|mut msg| { msg.topic = msg.topic.to_lowercase(); msg.metadata.insert( "processed_at".to_string(), current_timestamp().to_string() ); Ok(msg) }) .add_stage(|msg| { match &msg.content { MessageContent::Text(text) if text.len() > 10000 => { Err("Message too large".to_string().into()) } _ => Ok(msg) } })}This pipeline validates that messages have non-empty topics, normalizes the topic to lowercase, adds processing metadata, and finally checks that text messages aren’t too large. Each stage is independent and testable. The pipeline can be extended with new stages without modifying existing ones.
The beauty of this approach is how naturally it composes. Each closure captures exactly what it needs. The pipeline handles the plumbing of threading values through stages and error handling. The result is code that’s both flexible and easy to understand.
Summary
Section titled “Summary”This chapter looked at functional programming patterns that have their roots in languages such as Lisp, ML, and Haskell. Many years of research and practice have refined these ideas. What makes these patterns valuable in Rust is not that they’re new discoveries, but how Rust adapts them for systems programming with zero-cost abstractions and compile-time safety guarantees.
Function pipelines have been fundamental to functional programming since the 1970s. Rust makes them practical for systems code by compiling iterator chains to efficient machine code while maintaining ownership guarantees.
Type classes originated in Haskell in 1989 as a solution to ad hoc polymorphism. Rust’s trait system adapts this concept for systems programming, integrating type-class–style abstraction with lifetime tracking and zero-cost dispatch.
Pattern matching has been central to ML-family languages since 1973. Rust integrates it with move semantics and the borrow checker, providing exhaustiveness checking and safety guarantees appropriate for systems programming.
Lisp lambdas, the predecessor to closures, were first used in 1958. Rust’s three closure traits (Fn, FnMut, and FnOnce) explicitly encode ownership semantics, making closure-based patterns safe and efficient without garbage collection.
The Samsa microservice development throughout this chapter demonstrates how these discovered patterns create code that is more maintainable, testable, and reliable than traditional approaches. Importantly, these patterns complement rather than replace the architectural and type system patterns from previous chapters.
As you apply these patterns in your own work, remember that they represent discoveries made by developers solving real problems. The same process of recognizing recurring challenges and finding elegant solutions is something you can apply in your own projects. The best patterns emerge from practical experience, not from following prescribed methodologies.