Skip to content
ImagineWorld

Patterns Emerging from Rust's Core Features

node_idnode-book_design-patterns-and-best-practices-in-rust_chapter-12-patterns-emerging-from-rusts-core-features
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num12
chapter_titlePatterns Emerging from Rust's Core Features
pillar_membershipJ — architecture_design_craft
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Chapter 12 — Patterns Emerging from Rust’s Core Features

Section titled “Chapter 12 — Patterns Emerging from Rust’s Core Features”

12 Patterns Emerging from Rust’s Core Features

Section titled “12 Patterns Emerging from Rust’s Core Features”

This chapter focuses on how Rust adapts well-established programming concepts for systems programming. The Result and Option types come from functional programming languages such as Meta Language, or ML (1973), and Haskell (1990). Expression-oriented programming with blocks has roots in languages such as Lisp (1958) and Scheme (1975). Resource acquisition is initialization (RAII) originated in C++ in the 1980s.

You may be expecting me to say that the reason these patterns are so valuable for us is the way Rust enables and enhances them, and that’s true! Result and Option come from previous languages, but Rust makes them feel magical. Block expressions are ancient by programming standards, but they fit very naturally into Rust code to make it cleaner and more expressive. RAII has been around for quite some time, but the way that pattern interacts with Rust makes it integral to resource management with ironclad guarantees. All of this comes together to produce elegant, concise code.

At this point, as we near the end of the book, you will have heard this quite a bit. What makes this chapter different is that these patterns could be considered the “furniture” of the language. They are not just things that work in Rust; they are integral to it. As you read through these patterns, pay attention to what Rust adds to these established concepts, but also how they grow out of the language itself. It’s not only about making them practical for systems programming; it’s about making them essential Rust.

In this chapter, we’re going to cover the following main topics:

  • The Result and Option patterns, which transform error handling from burden to advantage

Block expression patterns that leverage Rust’s expression-oriented nature for cleaner code RAII patterns that use Rust’s ownership system for automatic resource management Patterns exemplifying elegance and conciseness that show how Rust enables expressive, readable code

The Result and Option types come from functional programming languages, particularly ML and Haskell, where they’re known as Either/Maybe and Result/Option, respectively. These languages established the approach of encoding errors and absence in the type system rather than using exceptions or null values. OCaml, F#, Scala, and Swift also use similar sum-type patterns for error handling.

Behind these patterns is the design philosophy that errors and absence are values, not exceptional control flow. Rather than interrupting program execution with exceptions or requiring defensive null checks scattered throughout code, Result and Option make failure modes explicit in function signatures. This forces callers to acknowledge and handle all possible outcomes at compile time, eliminating entire categories of runtime bugs such as null pointer exceptions and unhandled errors.

Working with Result and Option effectively means embracing functional programming patterns that transform and compose these types. Combinators such as map, and_then, and unwrap_or let you chain operations without explicit matching at every step. Error transformation with map_err converts between error types as values flow through your system. Early return composition using the ? operator threads success through pipelines while short-circuiting on failure. Fallback patterns provide defaults or alternative computations when operations fail. These patterns combine to create code that handles errors explicitly yet remains concise and readable. Patterns Emerging from Rust’s Core Features

In this section, we’ll see these patterns applied throughout our Samsa microservice, from configuration loading that gracefully handles missing files and invalid values to message-processing pipelines that compose multiple fallible operations.

What Rust brings to these well-established types is integration with ownership and zero-cost abstractions. Result and Option in Rust respect move semantics and borrowing rules, enabling safe error handling without garbage collection. Rust’s operator provides ergonomic error propagation while maintaining the explicit error handling that functional languages pioneered. The patterns that have developed around these types in Rust make working with them both safe and efficient for systems programming.

Configuration loading with error composition

Section titled “Configuration loading with error composition”

Every microservice needs configuration: ports, connection limits, storage paths, and feature flags. The traditional approach uses exceptions (try/catch) or error codes (check return values). Both have problems. Exceptions are uncontrolled by default, propagating beyond interface boundaries, sometimes even being invisible in function signatures. Error codes have the opposite issue because they are easy to ignore and need to be consciously handled.

In Samsa, configuration loading can fail in several ways: the file might not exist, the format might be wrong, or values might be invalid. Let’s see how Rust’s Result type enables clean, composable error handling.

Result takes two type parameters: a type for the value returned on success and an error type returned when there is an error. We can start by defining the configuration types that will be returned on success, so we have something to wrap in our Result:

#[derive(Debug, Clone)]
pub struct SamsaConfig {
pub broker: BrokerConfig,
pub log_level: String,
pub storage_path: String,
}
/// Broker-specific configuration
#[derive(Debug, Clone)]
pub struct BrokerConfig {
pub port: u16,
pub max_connections: usize,
pub buffer_size: NonZeroUsize,
pub connection_timeout: Duration,
pub enable_metrics: bool,

The SamsaConfig struct groups all broker configurations. Why separate fields instead of a HashMap? Type safety! The compiler ensures we use the right types, and the IDE autocomplete shows available options.

We’ll also implement the Default trait for these structs. This will make it simple to create and customize new configurations:

impl Default for SamsaConfig {
fn default() -> Self {
Self {
broker: BrokerConfig::default(),
log_level: "info".to_string(),
storage_path: "memory://".to_string(),
}
}
}
impl Default for BrokerConfig {
fn default() -> Self {
Self {
port: 8080,
max_connections: 1000,
buffer_size: NonZeroUsize::new(4096).unwrap(),
connection_timeout: Duration::from_secs(30),
enable_metrics: false,
}
}
}

These implementations provide sensible values for all of the fields, which we can use as a basis for our configurations. The default method can also provide a working configuration for development or testing.

We’ll be using SamsaError throughout this chapter. The full definition can be found in the GitHub repository:

#[derive(Error, Debug, Clone)]
pub enum SamsaError {
#[error("Configuration error: {0}")]
Config(String),
// ... More error variants
}
pub type Result<T> = std::result::Result<T, SamsaError>;
// Convenience constructors
impl SamsaError {
pub fn config(msg: impl Into<String>) -> Self {
SamsaError::Config(msg.into())
}
// ... other constructors as needed
}

SamsaError is an enum, not a generic error type. This granularity allows callers to handle different failures differently: retry on file-not-found errors, show parse errors to users, or log validation failures for debugging.

After setting up the configuration structure and error types, we can now implement the loading logic. Configuration loading follows a clear pipeline: read the file, parse the content, validate the values, and return the configuration. Let’s implement the loading logic:

impl SamsaConfig {
fn load_from_file<P: AsRef<Path>>(path: P) -> Result<Self> {
let content = fs::read_to_string(path)
.map_err(|_| SamsaError::config("Configuration file not found"))?;
Self::parse_config(&content)
}
}

The load_from_file method reads the configuration file and uses map_err to convert I/O errors into SamsaError::config(“Configuration file not found”). The ? operator propagates errors up the call stack. If reading succeeds, we pass the content to the parser.

Parsing extracts key-value pairs and populates the configuration:

fn parse_config(content: &str) -> Result<Self> {
let mut config = Self::default();
for line in content.lines() {
let line = line.trim();
if line.is_empty() || line.starts_with('#') {
continue;
}
if let Some((key, value)) = line.split_once('=') {
match key.trim() {
"broker_port" => {
config.broker.port = value.trim().parse()
.map_err(|_| SamsaError::config("Invalid port"))?;
}
"max_connections" => {
config.broker.max_connections = value.trim().parse()
.map_err(|_| SamsaError::config("Invalid max_connections"))?;
}
"log_level" => {
config.log_level = value.trim().to_string();
}
"storage_path" => {
config.storage_path = value.trim().to_string();
}
"buffer_size" => {
let size = value.trim().parse()
.map_err(|_| SamsaError::config("Invalid buffer_size"))?;
config.broker.buffer_size = NonZeroUsize::new(size)
.ok_or_else(|| SamsaError::config("buffer_size must be positive"))?;
}
_ => {} // Ignore unknown keys
}
}
}

config.validate()?; Ok(config) The parser iterates through lines, splits on ”=” and populates the configuration. Each parse error is converted to SamsaError: :config with a descriptive message. Notice that we start with a default configuration and override values found in the file. This provides sensible defaults for optional parameters.

After parsing, we validate the configuration:

fn validate(&self) -> Result<()> {
self.broker.validate()
}
impl BrokerConfig {
pub fn validate(&self) -> Result<()> {
if self.port == 0 {
return Err(SamsaError::config("Port cannot be zero"));
}
if self.port < 1024 {
return Err(SamsaError::config("Port cannot be in reserved range (0-1023)"));
}
if self.max_connections == 0 {
return Err(SamsaError::config("Max connections must be positive"));
}
Ok(())
}
}

The validation ensures required values meet constraints: port can’t be zero, and max_connections must be positive. This catches configuration errors early rather than failing mysteriously at runtime. If validation passes, parse_config returns Ok(config), which is the final step in our pipeline. The entire chain composes cleanly: load_from_file calls parse_config, which calls validate, and errors propagate automatically via ?.

Production systems load configuration from files, but having sensible defaults reduces boilerplate in tests and examples. Notice what Result gives us here: the compiler ensures every error path is handled, error types are explicit in function signatures (unlike exceptions), and operations are composed naturally through map_err and the ? operator. What happens when we need to load configuration from multiple sources? Samsa might check a local file, a user directory, and a system directory. Depending on the situation, we may either want to fail fast if any source fails or want to try each in order and collect the results.

Processing collections where operations might fail demonstrates how Result types compose naturally. The following examples show these patterns applied to configuration loading:

fn load_multiple_configs<P: AsRef<Path>>(
paths: &[P]
) -> Result<Vec<SamsaConfig>> {
paths
.iter()
.map(|path| SamsaConfig::load_from_file(path))
.collect::<Result<Vec<_>, _>>()
}
// Alternative with error collection
fn load_configs_with_fallback<P: AsRef<Path>>(
paths: &[P]
) -> (Vec<SamsaConfig>, Vec<SamsaError>) {
paths
.iter()
.map(|path| SamsaConfig::load_from_file(path))
.fold((Vec::new(), Vec::new()), |(mut configs, mut errors), result| {
match result {
Ok(config) => configs.push(config),
Err(error) => errors.push(error),
}
(configs, errors)
})
}

This pattern demonstrates Result’s strength: we can process collections of fallible operations and either fail fast (first function) or collect all results (second function). The types guide us toward correct error handling.

While Result handles errors, Option handles absence. In Samsa, many values are optional: message keys, metadata fields, and configuration overrides. We can use the same kind of combinators for handling Option values. Here’s an example using a Message type with optional headers:

impl Message {
fn get_header(&self, key: &str) -> Option<&str> {
self.headers.get(key).map(|s| s.as_str())
}
fn routing_key(&self) -> Option<&str> {
self.get_header("routing-key")
.or_else(|| self.get_header("topic"))
.filter(|k| !k.is_empty())
}
}

Option’s combinators mirror Result’s: map transforms the value, and then chains operations, or else provides fallbacks, and filter adds conditions. The pattern is consistent across both types.

Samsa needs to find the configuration from multiple locations, falling back gracefully when files are missing. The sequential fallback pattern chains fallible operations, trying each source in turn:

struct ServiceContext {
config: SamsaConfig,
}
impl ServiceContext {
fn load_config() -> Result<SamsaConfig> {
SamsaConfig::load_from_file("samsa.conf")
.or_else(|_| SamsaConfig::load_from_file("/etc/samsa/samsa.conf"))
.or_else(|_| SamsaConfig::load_from_file("/usr/local/etc/samsa.conf"))
.or_else(|_| {
eprintln!("Warning: Using default configuration");
Ok(SamsaConfig::default())
})
}
}

372

The or else combinator chains fallback attempts. Each closure only runs if the previous attempt failed. The final fallback provides a default, ensuring we always have a valid configuration. This is Result composition in action.

Samsa processes batches of incoming messages. Some will be valid, while others won’t. We don’t want one bad message to stop processing the entire batch. We want to collect successes and errors separately.

Processing message batches demonstrates Result’s power in handling collections of potentially failing operations. The following examples use specialized message types to focus on the patterns; the actual Samsa message structure (shown in the repository) differs slightly.

First, let’s define our message types:

#[derive(Debug)]
struct RawMessage {
data: Vec<u8>,
headers: std::collections::HashMap<String, String>,
}
#[derive(Debug)]
struct ProcessedMessage {
id: u64,
topic: String,
payload: Vec<u8>,
timestamp: std::time::SystemTime,
}

RawMessage represents unvalidated input with raw bytes and headers. ProcessedMessage is the final output with a generated ID, extracted topic, and timestamp.

Message processing follows a pipeline, beginning with a raw message and progressing through validation, transformation, enrichment, and processing. Each stage is a distinct type, ensuring that we cannot skip steps or process messages in the incorrect order.

The SamsaError enum captures failures at each stage: validation errors, missing fields, or enrichment problems. Let’s implement the validation stage:

impl RawMessage {
fn validate(self) -> Result<ValidatedMessage> {
if self.data.is_empty() {
Ok(())
}
// ...
}
}

The validate method checks that the message isn’t empty and returns a ValidatedMessage newtype. The newtype prevents accidentally using an unvalidated message. You must go through validation to get one.

Validated messages move to the transformation stage:

impl ValidatedMessage {
fn transform(self) -> Result<TransformedMessage> {
let topic = self.0.headers.get("topic")
.ok_or_else(|| SamsaError::broker("Missing topic"))?
.clone();
Ok(TransformedMessage {
topic,
data: self.0.data,
headers: self.0.headers,
})
}
}
struct TransformedMessage {
topic: String,
data: Vec<u8>,
headers: std::collections::HashMap<String, String>,
}

Transformation extracts structured data from the validated message. The topic comes from the headers. If it’s missing, we return an error. The TransformedMessage type represents a message with successfully extracted metadata. The final stage enriches the message with additional information:

impl TransformedMessage {
fn enrich(self) -> Result<ProcessedMessage> {
use std::time::SystemTime;
let id = self.headers.get("message_id")
.and_then(|s| s.parse().ok())
.unwrap_or_else(|| rand::random());
Ok(ProcessedMessage {
id,
topic: self.topic,
payload: self.data,
timestamp: SystemTime::now(),
})
}
}
fn process_message_batch(
messages: Vec<RawMessage>
) -> Result<Vec<ProcessedMessage>> {
messages
.into_iter()
.map(|msg| Result<ProcessedMessage> {
let validated = msg.validate()?;
let transformed = validated.transform()?;
Ok(transformed.enrich()?)
})
.collect()
}

Enrichment adds generated fields such as IDs and timestamps. The process_message_batch function chains all stages together, from validate to enrich, collecting successes and propagating errors.

This demonstrates the power of Result composition. Each stage returns Result, and the ? operator ensures that successful values travel through the entire pipeline while errors are caught immediately. The ? operator works here because our error types are all SamsaErrors, but we could also use different error types if all errors convert to SamsaError via the From trait. Without this conversion, the compiler would reject the code. The types ensure we can’t skip stages or reorder them incorrectly.

Expression-oriented programming, where blocks return values, has deep roots in functional programming. Lisp and its descendants made everything an expression. ML, Scheme, Haskell, OCaml, Scala, and Ruby all treat blocks as expressions that return values. This isn’t a Rust innovation but a fundamental concept from functional and expression-oriented languages.

What Rust adds is combining expression-oriented programming with the language’s guarantees. Blocks in Rust must respect ownership and borrowing rules. The compiler ensures that values returned from blocks are properly moved or borrowed. This integration of expression-oriented programming with compile-time memory safety makes complex initialization both safe and zero-cost, bringing functional programming elegance to systems code.

In many languages, statements do things and expressions produce values. In Rust, however, almost everything is an expression, including blocks, by which we mean code surrounded by { and }. A { … } block evaluates to its final expression, which can be assigned to a variable.

This matters because it lets us scope complex initialization logic while keeping the resulting assignment clean. Variables can be initialized from if/else blocks, match expressions, or arbitrary computation, all while respecting borrowing rules. We can call this pattern scoped initialization.

Let’s see how Samsa uses block expressions for configuration and initialization. Scoped Initialization makes the initialization logic very clean:

impl BrokerService {
pub fn new(config: BrokerConfig) -> Result<Self> {
let broker = {
let broker = Broker::new();
Arc::new(broker)
};
let connection_pool = {
if config.max_connections > 0 {
Some(ConnectionPool::new(config.max_connections))
} else {
None
}
}
}
};
let service = Self {
broker,
connection_pool,
config,
};
service.validate()?;
Ok(service)
}

The broker variable is initialized from a block that creates and wraps the broker in an Arc. The connection_pool block conditionally creates a pool only if max_connections is positive. Each block scopes its initialization logic while keeping the overall structure clean.

The final assignment builds the service struct, then validates it before returning. This pattern, where we initialize components, assemble them, and validate the result, is common in Rust service construction.

We can also use inline transformation blocks when creating configuration structs. Each field can be initialized from a block that transforms or validates its input:

fn create_connection_config(broker_config:&BrokerConfig)-> ConnectionConfig {
ConnectionConfig {
timeout: {
let secs = broker_config.connection_timeout.as_secs();
Duration::from_secs(match secs {
0 => 30,
t if t > 300 => 300,
t => t,
})
},
max_retries: {
if broker_config.enable_metrics {
5 // More retries when metrics enabled
} else {
}
},
}
}

This shows inline transformation blocks. The timeout field is initialized from a match block that clamps values to a valid range. The max_retries field uses a conditional block to set retries based on whether metrics are enabled.

For error handling, we can create immutable values in steps, each with error checking. This approach uses processing stage blocks:

fn process_client_request(request: RawRequest) -> Result<Response> {
let validated_request = {
request.validate_headers()?;
request.validate_payload()?;
request.parse_parameters()
.map_err(RequestError::InvalidParameters)?
};
let response_data = {
match validated_request.method.as_str() {
"PUBLISH" => {
let message = validated_request.extract_message()?;
ResponseData::Success { message_id: message.id }
}
method => return
}
Err(RequestError::UnsupportedMethod(method.to_string())),
}
};
Ok(Response { status: ResponseStatus::Ok, data: response_data })
}

This function demonstrates how block expressions create distinct processing phases, each with its own scope and clear purpose.

The first block handles request validation. It calls three validation methods in sequence, using ? to return early if any fail. The block’s value is the result of parse_parameters(). Notice that there’s no semicolon after it, making it the block’s return value. This validated request is then bound to validated_request.

The second block handles method dispatch. It matches on the request method and constructs the appropriate response data. The early return using return Err(…) for unsupported methods demonstrates that blocks can contain control flow that exits the entire function, not just the block.

Without blocks, this code would either use intermediate variables with less clear boundaries or nest everything in a single complex expression. Blocks let us write sequential validation logic that still produces a single value, combining the clarity of imperative steps with the composability of expressions.

Each block acts as a mini-function: it has inputs (variables from the surrounding scope), performs work, and produces a single output value. This makes the code’s structure mirror its intent: validate first, then process, then respond.

RAII was pioneered in C++ by Bjarne Stroustrup in the 1980s as a technique for automatic resource management through constructor–destructor pairs. The concept ties resource lifetime to object lifetime, ensuring cleanup happens automatically when objects go out of scope. C++, D, Ada, and other languages have used RAII patterns for decades.

Rust adapts RAII for memory-safe systems programming through its ownership system. Where C++ RAII relies on programmer discipline to avoid use-after-free and double-free errors, Rust’s ownership system enforces correct usage at compile time. The Drop trait provides deterministic destruction, such as C++ destructors, and the Rust borrow checker prevents accessing resources after they’ve been dropped. This makes RAII patterns both safe and predictable, eliminating entire classes of resource management bugs that plague C++ programs.

In Samsa, we manage connections, locks, and transactions. Each resource must be cleaned up properly: connections need to be returned to pools, locks must be released, and transactions should either be committed or rolled back. RAII ensures this cleanup happens automatically, even when errors occur.

The following examples demonstrate RAII patterns in Samsa’s resource management. First, let’s implement a connection pool with automatic cleanup:

struct ConnectionGuard {
connection: Option<Connection>,
pool: Arc<ConnectionPool>,
acquired_at: Instant,
}
impl Drop for ConnectionGuard {
fn drop(&mut self) {
if let Some(connection) = self.connection.take() {
// Record metrics about connection usage
let usage_duration = self.acquired_at.elapsed();
if usage_duration > Duration::from_secs(10) {
eprintln!("Warning: Connection held for {:?}",
usage_duration);
}
// Return connection to pool if it's still healthy
if connection.is_healthy() {
self.pool.return_connection(connection);
}
}
}

ConnectionGuard holds an Arc, ensuring the pool remains valid as long as any guard exists. When the guard is dropped, the Drop implementation checks whether the connection is still healthy and returns it to the pool for reuse. If the connection has been held too long, it logs a warning. This automatic cleanup happens regardless of how the scope exits, whether through a normal return, early return, or panic.

We can use this pattern to create a scoped lock with a timeout:

struct TimedLockGuard<'a, T> {
guard: Option<MutexGuard<'a, T>>,
acquired_at: Instant,
}
impl<'a, T> TimedLockGuard<'a, T> {
fn try_acquire(mutex: &'a Mutex<T>, timeout: Duration) -> Result<Self> {
let start = Instant::now();
loop {
match mutex.try_lock() {
Ok(guard) => return Ok(TimedLockGuard {
guard: Some(guard),
acquired_at: Instant::now(),
}),
Err(_) if start.elapsed() < timeout => {
std::thread::sleep(Duration::from_millis(1));

Err(_) => return Err(SamsaError::resource(“Lock acquisition timeout”)),

}
}
}
}

This pattern wraps lock acquisition with a timeout mechanism. The guard tracks when it was acquired, enabling metrics collection for lock hold times. The RAII pattern ensures the lock is released when the guard goes out of scope.

Let’s think about building a cascading cleanup for service shutdown. The Samsa ServiceManager delegates to BrokerService.shutdown(), which ensures resources are released:

impl Drop for ServiceManager {
fn drop(&mut self) {
if let Some(service) = self.broker_service.take() {
let _ = service.shutdown();
}
}
}

This ensures cleanup happens automatically, but in a controlled way.

This pattern can also be applied to create a transaction guard for data consistency:

struct TransactionGuard<'a> {
storage: &'a mut dyn Storage,
committed: bool,
}
impl<'a> TransactionGuard<'a> {
fn begin(storage: &'a mut dyn Storage) -> Result<Self> {
storage.begin_transaction()?;
Ok(TransactionGuard { storage, committed: false })
}
fn commit(mut self) -> Result<()> {
self.storage.commit_transaction()?;
}
}
self.committed = true;
Ok(())
}
impl<'a> Drop for TransactionGuard<'a> {
fn drop(&mut self) {
if !self.committed {
let _ = self.storage.rollback_transaction();
}
}
}

TransactionGuard borrows storage mutably, preventing any other code from accessing storage while a transaction is active. (The repository implementation uses a more flexible generic design with a rollback closure, but the RAII principle is identical.)

Rust enables remarkably elegant and concise code through patterns that leverage the language’s expression-oriented nature and powerful type system. The patterns we’ve explored, Result composition, Option combinators, block expressions, and RAII, aren’t meant to be used in isolation. They combine naturally to create code that’s both safe and readable.

This section shows how these patterns work together in Samsa’s subscription processing pipeline, demonstrating how Rust’s design principles lead to code that is both expressive and performant. We’ll see Result and Option for error handling, iterator chains for transformation, and newtypes for validation.

Samsa processes subscription requests in batches, validating user input, transforming it into internal formats, and activating subscriptions. Some requests will be valid, others won’t. We need to process all of them efficiently while tracking both successes and failures. Rust’s iterator and Result patterns make this kind of batch transformation both elegant and safe.

First, we define the request and subscription types used in the subscription pipeline:

use std::collections::HashMap;
#[derive(Debug)]
struct SubscriptionRequest {
user_id: u64,
topic: String,
qos_level: u8,
metadata: HashMap<String, String>,
}
#[derive(Debug)]
struct ActiveSubscription {
id: u64,
user_id: u64,
topic: String,
qos_level: u8,
created_at: std::time::SystemTime,
}

We’re creating a processing pipeline that validates requests and converts them to active subscriptions. A subscription request arrives from a user, gets validated, and becomes an active subscription. The pipeline will ultimately have three stages:

  1. SubscriptionRequest (raw user input)
  2. ValidatedSubscriptionRequest (checked for validity)
  3. ActiveSubscription (enriched with ID and timestamp)

These types model subscription requests and their processed results.

Let’s trace through each stage and implement the validation:

impl SubscriptionRequest {
fn validate(self) -> Result<ValidatedSubscriptionRequest> {
if self.user_id == 0 {
return Err(SamsaError::consumer("Invalid user ID"));
}
if self.topic.is_empty() || self.topic.len() > 255 {
return Err(SamsaError::topic("Invalid topic"));
}
if self.qos_level > 2 {
return Err(SamsaError::consumer("Invalid QoS level"));
}
Ok(ValidatedSubscriptionRequest(self))
}
}
struct ValidatedSubscriptionRequest(SubscriptionRequest);
impl TryFrom<ValidatedSubscriptionRequest> for ActiveSubscription {
type Error = SamsaError;
fn try_from(validated: ValidatedSubscriptionRequest) -> Result<Self, Self::Error> {
let req = validated.0;
Ok(ActiveSubscription {
id: rand::random(),
user_id: req.user_id,
topic: req.topic,
qos_level: req.qos_level,
created_at: std::time::SystemTime::now(),
})
}
}

The validate method checks the user ID, topic, and quality-of-service level. Valid requests become ValidatedSubscriptionRequest newtypes. The TryFrom implementation converts validated requests to active subscriptions. The separation of validate and convert makes each step explicit and testable.

Now let’s look at batch processing:

fn process_subscription_requests(
requests: Vec<SubscriptionRequest>
) -> (Vec<ActiveSubscription>, Vec<SamsaError>) {
requests
.into_iter()
.filter_map(|req| {
// Pre-filter obviously invalid requests
if req.topic.contains("..") || req.topic.starts_with('/') {
None
} else {
Some(req)
}
})
.map(|req| req.validate())
.filter_map(|result| result.ok()) // Keep only valid requests
.map(|validated| validated.try_into())
.fold((Vec::new(), Vec::new()), |(mut success, mut errors), result| {
match result {
Ok(subscription) => success.push(subscription),
Err(error) => errors.push(error),
}
(success, errors)
})
}

This function demonstrates iterator composition. It pre-filters invalid topics with filter_map, validates remaining requests, keeps only valid ones with filter_map, converts to active subscriptions with try_into, and separates successes from errors with fold.

The iterator chain reads from left to right like a pipeline. Each operation is lazy, with no intermediate allocations. The final fold partitions results into successes and errors, providing full visibility into batch processing outcomes.

The patterns we’ve seen, Result composition, Option combinators, and iterator chains, apply throughout Rust code. The following example shows how these patterns would apply to loading configuration from environment variables:

impl BrokerConfig {
fn from_env() -> Self {
Self {
port: env::var("SAMSA_PORT")
.ok()
.and_then(|s| s.parse().ok())
.unwrap_or(8080),
max_connections: env::var("SAMSA_MAX_CONN")
.ok()
.and_then(|s| s.parse().ok())
.filter(|&n| n > 0 && n <= 10000)
.unwrap_or(1000),
}
}
}

Notice the familiar pattern: ok() converts Result to Option, and_then() chains transformations, filter() validates values, and unwrap_or() provides defaults. These aren’t separate techniques. They’re aspects of a unified approach where types and combinators work together to create concise, safe code. Note

Is unwrap_or safe?

unwrap_or() is safe here because we’re providing a fallback value, not panicking. The ok().and_then().unwrap_or() pattern never panics. It gracefully degrades to defaults when environment variables are missing or invalid.

Smart constructors, such as the validated topic pattern that we’ve seen, combine validation with type creation. They serve as the sole entry point for constructing a type, guaranteeing that all instances are valid from the outset:

pub struct ValidatedTopic(String);
impl ValidatedTopic {
pub fn new(topic: impl AsRef<str>) -> Result<Self> {
let topic = topic.as_ref();
if topic.is_empty() { return Err(SamsaError::topic("Topic cannot be empty")); }
if topic.len() > 255 { return Err(SamsaError::topic("Topic too long")); }
if !topic.chars().all(|c| c.is_alphanumeric() || "./_-".contains(c)) {
return Err(SamsaError::topic("Invalid characters in topic"));
}
Ok(ValidatedTopic(topic.to_string()))
}
pub fn as_str(&self) -> &str {
&self.0
}
}

This pattern appears in our configuration loading, message validation, and subscription processing. It’s fundamental to Rust’s approach of encoding invariants in types. The builder pattern we explored earlier follows the same principle: validate at construction, then work with guaranteed valid types.

Throughout this section, we’ve seen how Result composition, Option combinators, iterator chains, and smart constructors work together naturally. Each pattern handles one concern, such as error propagation, absence, transformation, or validation, and they combine without friction. This is the elegance Rust enables: small, focused patterns that compose into larger solutions without losing clarity or safety.

This chapter explored patterns that are, as we noted at the start, the “furniture” of Rust. Where previous chapters explored techniques that work in the language, these are patterns that grow out of Rust’s very design. Result and Option transform error handling from a burden into an expressive tool. Block expressions leverage Rust’s expression-oriented nature for scoped, clean initialization. RAII patterns provide automatic cleanup with zero runtime cost. Rust’s design enables remarkably concise yet readable code because of what is built into the language.

These patterns have deep roots in programming language research and practice. Rust integrates them while adapting these concepts for systems programming and memory safety guarantees.

We saw this throughout the Samsa microservice: configuration loading that composes naturally through Result, service initialization that uses blocks to contain complexity, and connection pools and transaction guards that clean up automatically. These patterns solved practical problems. More importantly, they felt like the natural way to solve them in Rust.

That’s what makes these patterns furniture. You don’t think about a chair as “sitting technology”; you just sit. Similarly, experienced Rust developers don’t think, “I’ll use the Result composition pattern here”; they just propagate errors with ? and move on. The patterns become invisible through familiarity, part of how you think in the language.

As Rust continues to evolve and developers tackle new challenges, new ways of combining these features will emerge. Remember that patterns are tools to serve your goals, not rules to constrain your thinking. When you encounter new challenges, draw inspiration from these patterns, but don’t hesitate to develop new approaches when existing patterns don’t fit. The Rust community’s strength lies in its willingness to share discoveries and build upon each other’s work.

As you continue writing Rust, you’ll find these patterns appearing without conscious effort. That’s the goal. When Result composition, block expressions, and RAII become second nature, you will move beyond using Rust and begin thinking in it. Patterns Emerging from Rust’s Core Features