Skip to content
ImagineWorld

Creational Patterns in Rust

node_idnode-book_oop-to-rust_chapter-13-creational-patterns-in-rust
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num13
chapter_titleCreational Patterns in Rust
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Chapter 13 — Creational Patterns in Rust

Section titled “Chapter 13 — Creational Patterns in Rust”

Faber est suae quisque fortunae. (Every man is the architect of his own fortune.)

Object creation in OOP languages relies heavily on constructors and inheritance. A base class constructor initializes shared state; subclass constructors call the parent and add their own initialization. Factory methods return different subclass instances based on parameters. Abstract factories create families of related objects. These patterns assume class hierarchies and constructor overloading, neither of which Rust provides.

The importance of creation patterns stems from the complexity of object initialization. Objects often require validation, resource acquisition, computed default values, or coordination with other systems. A simple field assignment does not suffice. The patterns encapsulate this complexity, presenting clean creation interfaces while hiding the intricate initialization logic within.

Rust has no constructors in the OOP sense. There is no new keyword, no special method that runs automatically when a type is instantiated, no constructor chaining from child to parent. Struct instantiation uses struct literal syntax, filling in fields directly. This simplicity forces a rethinking of creational patterns, and the results are often cleaner than their OOP counterparts.

The absence of constructors is not a limitation but a design choice. Constructors in OOP carry implicit behavior: they run automatically, they chain through inheritance hierarchies, they may throw exceptions before the object exists. Rust’s explicit approach makes creation visible and controllable. Every object creation is a function call or struct literal, with no hidden magic. This explicitness aligns with Rust’s philosophy of making behavior obvious.

This chapter examines how the classic creational patterns translate to Rust. The Builder pattern gains type-level guarantees through the typestate pattern. Factories become associated functions with no need for inheritance. The Singleton pattern, always controversial, finds safer alternatives in Rust’s ownership system. The Prototype pattern maps directly to the Clone trait. Each translation reveals how Rust’s constraints lead to designs that are both idiomatic and robust.

The patterns are presented in increasing conceptual complexity. Associated functions provide the foundation, replacing basic constructors. Factories build on this foundation, abstracting over what type to create. Builders handle complex configuration with many parameters. Singletons address resource sharing across the application. The Prototype pattern provides efficient object cloning. Understanding earlier patterns helps with understanding later ones.

Throughout, the chapter emphasizes idiomatic Rust over direct translation. A pattern that works in Java might have a better Rust alternative. The goal is not just making the pattern compile but making it feel natural to Rust developers. Code should leverage Rust’s strengths: explicit ownership, powerful type system, trait-based abstraction.

Associated functions as constructors

Rust’s convention for object creation uses associated functions, typically named new. An associated function belongs to a type rather than an instance; it appears in an impl block but takes no self parameter. The new function returns an instance of the type, performing whatever initialization is necessary.

This approach differs fundamentally from OOP constructors. In Java or C#, constructors are special methods invoked through the new keyword. The language provides guarantees: constructors run exactly once per object, before any other methods. Subclass constructors chain to superclass constructors. The language ensures the object is fully initialized before use.

Rust’s associated functions carry no such guarantees because Rust has no class hierarchy to chain through. An associated function is a function that happens to return a new instance. The compiler does not distinguish it from any other function. This simplicity has consequences: there is no automatic chaining, no guaranteed initialization order, no special error handling for construction failures.

The following example shows the basic pattern:

pub struct Rectangle {
width: u32,
height: u32,
}
impl Rectangle {
pub fn new(width: u32, height: u32) -> Self {
Rectangle { width, height }
}
pub fn square(size: u32) -> Self {
Rectangle { width: size, height: size }
}
}

The new function is purely conventional. Nothing forces types to provide it, and the name carries no special meaning to the compiler. Other constructors can coexist with different names reflecting their purpose. The square function creates a rectangle with equal sides, a named constructor that makes intent explicit.

This convention emerged from the Rust community rather than language design. The compiler treats new like any other associated function. Yet nearly every Rust library follows this pattern, creating a strong expectation. Users encountering a new type look for new first. Deviating from the convention requires justification: perhaps the type has no sensible default construction, or perhaps multiple equally valid constructors exist with no clear primary.

Named constructors go further than constructor overloading. In languages with overloading, parameter types distinguish constructors. A Rectangle might have constructors taking (width, height) and (side), distinguished by argument count. The caller writes new Rectangle(10) and hopes the compiler selects the intended overload. In Rust, the name carries meaning: Rectangle::square(10) states the intent explicitly. The constructor name documents the construction mode.

This pattern replaces constructor overloading. In Java, multiple constructors with different parameter lists provide various ways to create an object. In Rust, multiple associated functions with descriptive names serve the same purpose with greater clarity. A caller reads Rectangle::square(10) and understands the intent without consulting documentation.

Fallible construction uses Result as the return type. When creation might fail (invalid parameters, resource allocation failures, parsing errors), the constructor returns Result<Self, Error> rather than panicking or returning a partially initialized object.

This design pattern appears throughout Rust’s ecosystem. File operations that might fail return Result<File, io::Error>. Network connections return Result<TcpStream, io::Error>. Database connections return Result<Connection, DatabaseError>. The pattern is so common that most Rust developers expect fallible operations to return Result.

The following example shows a constructor that validates its inputs:

pub struct DatabaseConnection {
connection_string: String,
pool_size: usize,
}
impl DatabaseConnection {
pub fn new(connection_string: &str, pool_size: usize) -> Result<Self, ConnectionError> {
if connection_string.is_empty() {
return Err(ConnectionError::EmptyConnectionString);
}
if pool_size == 0 {
return Err(ConnectionError::InvalidPoolSize);
}
Ok(DatabaseConnection {
connection_string: connection_string.to_string(),
pool_size,
})
}
}

The caller must handle the Result, making failure explicit at every construction site. This eliminates the ambiguity of constructors that throw exceptions in some cases and succeed in others.

The distinction matters for reasoning about code. When constructors can throw, every object creation is potentially a failure point. The new keyword offers no visual indication of fallibility. In Rust, the return type declares intent: Self for infallible construction, Result<Self, E> for fallible. A function signature communicates what might go wrong before reading any implementation code.

This approach also prevents partially constructed objects. In languages with exceptions, a constructor might fail midway through initialization, leaving fields in inconsistent states. Finalizers, destructors, or garbage collection must handle these half-initialized objects. Rust’s approach either succeeds with a fully constructed value or fails with an error, never producing an intermediate state.

Factory patterns via associated functions

The Factory Method pattern in OOP uses inheritance: a base class defines a method that returns a product interface, and subclasses override it to return concrete products. The pattern decouples the client from concrete product types, allowing subclasses to determine which product to create.

Understanding the factory pattern requires understanding the problem it solves. Consider code that creates database connections. If the code directly instantiates PostgresConnection, it cannot work with MySQL or SQLite without modification. The connection type is hardcoded. Testing requires a real Postgres database. Switching databases requires changes at every creation site.

Factories introduce an abstraction layer. Instead of creating connections directly, code requests connections from a factory. The factory decides which concrete type to create. Client code works with the abstract connection interface, ignorant of the underlying implementation. Swapping databases means providing a different factory, not modifying client code.

The OOP implementation typically involves inheritance. A base factory class declares an abstract method. Subclasses override it to create specific products. Rust achieves the same decoupling through traits rather than inheritance.

The following sections explore how Rust implements factory patterns. First comes the basic factory using traits, which closely mirrors the OOP approach. Then comes the enum-based approach for closed sets of products. Finally, the abstract factory pattern shows how to create families of related products.

The motivation for factories is dependency inversion. Client code should depend on abstractions, not concretions. When code directly instantiates a concrete type, it becomes coupled to that type. Changing the concrete type requires modifying every instantiation site. Factories centralize creation decisions, allowing the concrete type to change in one place while client code remains unchanged.

Factories also enable testing. Code that directly creates database connections cannot be tested without a real database. Code that receives a connection factory can be tested with a mock factory that creates fake connections. The factory abstraction creates a seam for testing, isolating the code under test from its dependencies.

In Rust, traits replace the inheritance relationship. A factory trait defines the creation method, and different types implement it to produce different products. The trait declares what factories do (create products) while implementations decide how (which concrete product to create).

This approach has several advantages over inheritance-based factories. Traits can be implemented for existing types without modifying them. A single type can implement multiple factory traits.

There is no fragile base class problem because there is no base class. The factory abstraction exists only at the trait level, with no runtime inheritance overhead.

The following example shows a document factory using this approach:

pub trait Document {
fn render(&self) -> String;
}
pub struct PdfDocument {
content: String,
}
impl Document for PdfDocument {
fn render(&self) -> String {
format!("PDF: {}", self.content)
}
}
pub struct HtmlDocument {
content: String,
}
impl Document for HtmlDocument {
fn render(&self) -> String {
format!("<html>{}</html>", self.content)
}
}
pub trait DocumentFactory {
fn create(&self, content: &str) -> Box<dyn Document>;
}
pub struct PdfFactory;
impl DocumentFactory for PdfFactory {
fn create(&self, content: &str) -> Box<dyn Document> {
Box::new(PdfDocument { content: content.to_string() })
}
}
pub struct HtmlFactory;
impl DocumentFactory for HtmlFactory {
fn create(&self, content: &str) -> Box<dyn Document> {
Box::new(HtmlDocument { content: content.to_string() })
}
}

Client code receives a &dyn DocumentFactory and creates documents without knowing the concrete type. The factory abstraction enables dependency injection and testing: a test can provide a mock factory that creates stub documents.

The trait-based approach mirrors OOP factories while fitting Rust’s type system. The factory trait declares the creation contract. Each implementing type decides which concrete product to create. Client code programs against the trait, remaining ignorant of concrete types until runtime. This inversion of control separates the decision of what to create from the code that uses the created object.

One notable difference from OOP factories: Rust factories typically return Box<dyn Trait> rather than raw trait objects. The box provides heap allocation and ownership transfer. In OOP languages, garbage collection handles the returned object’s lifetime. In Rust, the box makes ownership explicit: the caller owns the created object and is responsible for its eventual deallocation.

When the set of products is known and closed, enums offer a simpler approach. Instead of trait objects and separate factory types, a single factory function returns an enum. This approach trades extensibility for simplicity and performance: enums are stack-allocated, avoid virtual dispatch, and enable exhaustive pattern matching.

The enum approach represents a fundamental design choice in Rust. Where OOP tends toward open extension through inheritance, Rust provides both open extension (through traits) and closed extension (through enums). Choosing the right approach depends on the application’s evolution requirements. Systems expecting frequent new product types benefit from traits. Systems with stable product sets benefit from enums.

The following example demonstrates the enum-based factory approach:

pub enum Document {
Pdf { content: String },
Html { content: String },
}
impl Document {
pub fn render(&self) -> String {
match self {
Document::Pdf { content } => format!("PDF: {}", content),
Document::Html { content } => format!("<html>{}</html>", content),
}
}
}
pub fn create_document(format: &str, content: &str) -> Result<Document, FormatError> {
match format {
"pdf" => Ok(Document::Pdf { content: content.to_string() }),
"html" => Ok(Document::Html { content: content.to_string() }),
_ => Err(FormatError::UnknownFormat(format.to_string())),
}
}

This approach works when extensibility is not required. The match arms enumerate all cases; adding a format requires modifying the function. For applications where document formats are fixed at compile time, the enum approach provides pattern matching benefits and avoids heap allocation.

The choice between traits and enums reflects a fundamental design decision. Traits provide open extensibility: new implementations can be added without modifying existing code. This suits libraries where users define their own types. Enums provide closed extensibility: all variants are known at compile time. This enables exhaustive matching and guarantees that all cases are handled. The compiler warns when match statements miss variants, catching errors when new variants are added.

In practice, the decision often depends on who extends the system. If extension happens across crate boundaries (users adding their own document types), traits are necessary. If extension happens within a single crate (developers adding formats to a fixed set), enums often produce simpler code.

The Abstract Factory pattern, which creates families of related products, translates similarly. A trait defines methods for creating each product in the family. Implementations produce compatible sets.

The abstract factory addresses a coordination problem. When creating multiple related objects, consistency matters. A button and a checkbox in the same UI should share visual style. A request and response handler should share protocol assumptions. Creating these objects independently risks inconsistency; grouping them in a factory ensures they match.

The trait-based abstract factory declares all creation methods in a single interface. Each implementation provides compatible products for its family. Client code receives a factory and uses it for all related object creation, guaranteeing consistency.

The following example demonstrates an abstract factory for platform-specific UI widgets:

// Product traits
pub trait Button {
fn render(&self) -> String;
fn on_click(&self, handler: Box<dyn Fn()>);
}
pub trait Checkbox {
fn render(&self) -> String;
fn is_checked(&self) -> bool;
fn toggle(&mut self);
}
// Abstract factory trait
pub trait UiFactory {
fn create_button(&self, label: &str) -> Box<dyn Button>;
fn create_checkbox(&self, label: &str, checked: bool) -> Box<dyn Checkbox>;
}
// Windows implementation
pub struct WindowsButton { label: String }
pub struct WindowsCheckbox { label: String, checked: bool }
impl Button for WindowsButton {
fn render(&self) -> String {
format!("[Windows Button: {}]", self.label)
}
fn on_click(&self, _handler: Box<dyn Fn()>) {}
}
impl Checkbox for WindowsCheckbox {
fn render(&self) -> String {
let mark = if self.checked { "X" } else { " " };
format!("[{}] {}", mark, self.label)
}
fn is_checked(&self) -> bool { self.checked }
fn toggle(&mut self) { self.checked = !self.checked; }
}
pub struct WindowsFactory;
impl UiFactory for WindowsFactory {
fn create_button(&self, label: &str) -> Box<dyn Button> {
Box::new(WindowsButton { label: label.to_string() })
}
fn create_checkbox(&self, label: &str, checked: bool) -> Box<dyn Checkbox> {
Box::new(WindowsCheckbox { label: label.to_string(), checked })
}
}
// macOS implementation
pub struct MacButton { label: String }
pub struct MacCheckbox { label: String, checked: bool }
impl Button for MacButton {
fn render(&self) -> String {
format!("( {} )", self.label)
}
fn on_click(&self, _handler: Box<dyn Fn()>) {}
}
impl Checkbox for MacCheckbox {
fn render(&self) -> String {
let mark = if self.checked { "✓" } else { " " };
format!("({}) {}", mark, self.label)
}
fn is_checked(&self) -> bool { self.checked }
fn toggle(&mut self) { self.checked = !self.checked; }
}
pub struct MacFactory;
impl UiFactory for MacFactory {
fn create_button(&self, label: &str) -> Box<dyn Button> {
Box::new(MacButton { label: label.to_string() })
}
fn create_checkbox(&self, label: &str, checked: bool) -> Box<dyn Checkbox> {
Box::new(MacCheckbox { label: label.to_string(), checked })
}
}
// Client code using the factory
fn render_ui(factory: &dyn UiFactory) {
let button = factory.create_button("Submit");
let checkbox = factory.create_checkbox("Remember me", false);
println!("{}", button.render());
println!("{}", checkbox.render());
}

The trait ensures that each factory produces a consistent set of widgets. Client code parameterized by &dyn UiFactory creates platform-appropriate UI elements without platform-specific conditionals.

The abstract factory pattern becomes particularly valuable in cross-platform applications. Rather than scattering platform checks throughout the codebase, a single decision at startup selects the appropriate factory. All subsequent widget creation flows through this factory, ensuring consistency. Adding a new platform means implementing a new factory, not modifying every widget creation site.

The pattern also enables theming without inheritance hierarchies. A dark mode factory and a light mode factory can produce visually different widgets while implementing the same trait. The application switches themes by switching factories, without the widget creation code knowing or caring about themes.

The relationship between products and factories deserves attention. The abstract factory ensures products work together. A WindowsFactory produces WindowsButton and WindowsCheckbox that share visual style and behavior patterns. Mixing products from different factories (a Windows button with a Mac checkbox) would produce inconsistent UI. The abstract factory prevents this by constraining which products can be combined.

Generic factories provide another approach. Instead of trait objects, a factory function takes a type parameter specifying the product family. This approach uses static dispatch, avoiding trait object overhead at the cost of less runtime flexibility. The choice depends on whether the factory type is known at compile time or determined at runtime.

The builder pattern

The Builder pattern addresses the construction of complex objects with many configuration options. It separates the construction process from the representation, allowing the same construction process to create different representations. The pattern is particularly valuable when objects have numerous optional fields, when construction requires multiple steps, or when the object should be immutable after creation.

Complex objects with many optional fields challenge simple constructors. A struct with ten fields, five of them optional, would require either numerous constructor overloads or a constructor taking many nullable parameters. Neither approach scales well or communicates intent clearly.

The pattern originated in the Gang of Four book but has evolved significantly in modern usage. The original formulation emphasized separating construction logic into a separate Director class that orchestrated the building process. Modern usage, particularly in fluent APIs, typically combines director and builder functionality, using method chaining to create a readable construction sequence.

Consider the problem from the caller’s perspective. A constructor with ten parameters, most of them optional, forces callers to remember parameter order, pass placeholders for unwanted options, and decipher long argument lists. Reading new(url, “POST”, headers, null, null, null, body, 30000, null, null) does not communicate which options were set and which were defaulted. The call site becomes a puzzle.

Constructor overloading helps but does not solve the problem. Each combination of optional parameters needs its own constructor. With five optional parameters, the number of combinations explodes. Constructors with similar parameter types become ambiguous. The solution creates more problems than it solves.

The Builder pattern addresses this by accumulating configuration through method calls, then producing the final object. Each setter method returns the builder, enabling method chaining. A terminal method consumes the builder and returns the constructed object. Configuration becomes explicit: only set options appear in the code, with names that explain their purpose.

The builder acts as an intermediate representation. It holds partially specified configuration, accumulating fields as methods are called. Unlike the final object, the builder allows incomplete states: not all fields need values at every moment. The build method transforms this intermediate state into the final object, validating completeness and applying defaults.

Method chaining produces readable configuration. Each method call appears on its own line, describing a single configuration aspect. The method names document their purpose. The values are visible alongside the setting names. Reading the builder chain reveals the complete configuration without cross-referencing documentation or counting parameter positions.

The following example demonstrates an HTTP request builder:

pub struct HttpRequest {
url: String,
method: String,
headers: Vec<(String, String)>,
body: Option<String>,
timeout_ms: u32,
}
pub struct HttpRequestBuilder {
url: String,
method: String,
headers: Vec<(String, String)>,
body: Option<String>,
timeout_ms: u32,
}
impl HttpRequestBuilder {
pub fn new(url: &str) -> Self {
HttpRequestBuilder {
url: url.to_string(),
method: "GET".to_string(),
headers: Vec::new(),
body: None,
timeout_ms: 30000,
}
}
pub fn method(mut self, method: &str) -> Self {
self.method = method.to_string();
self
}
pub fn header(mut self, name: &str, value: &str) -> Self {
self.headers.push((name.to_string(), value.to_string()));
self
}
pub fn body(mut self, body: &str) -> Self {
self.body = Some(body.to_string());
self
}
pub fn timeout(mut self, ms: u32) -> Self {
self.timeout_ms = ms;
self
}
pub fn build(self) -> HttpRequest {
HttpRequest {
url: self.url,
method: self.method,
headers: self.headers,
body: self.body,
timeout_ms: self.timeout_ms,
}
}
}

Usage reads naturally, with each configuration step explicit:

let request = HttpRequestBuilder::new("https://api.example.com/users")
.method("POST")
.header("Content-Type", "application/json")
.body(r#"{"name": "Alice"}"#)
.timeout(5000)
.build();

Compare this to the equivalent constructor call. The builder version is longer but clearer. Each line documents a configuration choice. The method("POST") call states the HTTP method. The header call shows the content type. The body call shows the payload. The timeout call shows the duration. A reader understands the request without knowing parameter order or default values.

The builder also handles defaults naturally. The new function establishes sensible defaults (GET method, empty headers, no body, second timeout). Configuration calls override specific defaults. The final request uses a mix of explicit settings and defaults, with the explicit settings visible in the code and the defaults documented in the builder’s new function.

The builder methods take self by value and return Self, consuming and returning ownership. This allows chaining and ensures the builder cannot be reused after modifications. Taking mut self allows in-place mutation before returning, avoiding unnecessary allocations.

The ownership transfer through self has implications for API design. Once a method is called, the original builder binding becomes invalid. The returned builder must be captured for further configuration. This prevents accidental reuse of intermediate states and makes the flow of ownership explicit in the code.

The pattern also enables validation at each step. A method setting a port number can validate the range immediately, returning an error or panicking before the invalid value propagates. Early validation fails fast, producing clearer error messages than deferred validation at build time.

A variation takes &mut self and returns &mut Self, allowing the builder to be reused:

impl HttpRequestBuilder {
pub fn method(&mut self, method: &str) -> &mut Self {
self.method = method.to_string();
self
}
pub fn build(&self) -> HttpRequest {
HttpRequest {
url: self.url.clone(),
method: self.method.clone(),
headers: self.headers.clone(),
body: self.body.clone(),
timeout_ms: self.timeout_ms,
}
}
}

This approach clones data in build, allowing multiple objects to be created from the same builder with variations. The choice depends on whether builder reuse is valuable for the use case.

The choice between consuming and borrowing builders involves trade-offs. Consuming builders are simpler to implement and use, enforcing a linear flow from creation to configuration to building. Borrowing builders add flexibility at the cost of cloning data. Libraries often provide consuming builders, while application code might use borrowing builders when creating many similar objects from a template.

Typestate builder pattern

The standard builder pattern catches configuration errors at runtime. Calling build might fail because required fields were never set. The typestate pattern encodes the builder’s state in its type, making invalid states unrepresentable and catching configuration errors at compile time.

The idea behind typestate is that different states of an object should have different types. A file handle in “open” state and a file handle in “closed” state should be different types, preventing reads from closed files at compile time. A builder before setting required fields and a builder after setting them should be different types, preventing premature builds at compile time.

This technique exploits Rust’s type system for correctness. The compiler tracks type state automatically through normal type inference. Incorrect sequences of operations become type errors. The runtime cost is zero: the type parameters exist only during compilation and disappear in the generated code.

Consider a connection builder that requires both host and port before building. Without typestate, the build method must check at runtime whether both fields were set, returning an error or panicking if not. With typestate, the build method only exists when the type indicates both fields are set. The runtime check becomes unnecessary because the type system already verified the condition.

The typestate approach uses generic type parameters to track which fields have been set:

pub struct NoHost;
pub struct HasHost(String);
pub struct NoPort;
pub struct HasPort(u16);
pub struct ConnectionBuilder<H, P> {
host: H,
port: P,
timeout: Option<u32>,
}
impl ConnectionBuilder<NoHost, NoPort> {
pub fn new() -> Self {
ConnectionBuilder {
host: NoHost,
port: NoPort,
timeout: None,
}
}
}
impl<P> ConnectionBuilder<NoHost, P> {
pub fn host(self, host: &str) -> ConnectionBuilder<HasHost, P> {
ConnectionBuilder {
host: HasHost(host.to_string()),
port: self.port,
timeout: self.timeout,
}
}
}
impl<H> ConnectionBuilder<H, NoPort> {
pub fn port(self, port: u16) -> ConnectionBuilder<H, HasPort> {
ConnectionBuilder {
host: self.host,
port: HasPort(port),
timeout: self.timeout,
}
}
}
impl<H, P> ConnectionBuilder<H, P> {
pub fn timeout(mut self, ms: u32) -> Self {
self.timeout = Some(ms);
self
}
}
impl ConnectionBuilder<HasHost, HasPort> {
pub fn build(self) -> Connection {
Connection {
host: self.host.0,
port: self.port.0,
timeout: self.timeout,
}
}
}

The build method exists only for ConnectionBuilder<HasHost, HasPort>. Attempting to build without setting both host and port produces a compile error. The type system tracks progress through the configuration, and the compiler enforces completeness.

This approach transforms runtime errors into compile-time errors. A forgotten host() call in traditional builder code might surface as a runtime panic, possibly in production, possibly after a user action triggered the code path. With typestate, the same mistake produces an immediate compiler error with a clear message about missing method calls.

The generic parameters act as phantom state markers. They carry no runtime data (the marker types contain String and u16, but only when set). The compiler uses these types to control method availability, then erases them in the generated machine code. The abstraction costs nothing at runtime.

The following diagram illustrates the typestate transitions:

graph TD
    S(( )) -- "new()" --> NN["NoHost_NoPort"]
    NN -- "host()" --> HN["HasHost_NoPort"]
    NN -- "port()" --> NH["NoHost_HasPort"]
    HN -- "port()" --> HH["HasHost_HasPort"]
    NH -- "host()" --> HH
    HH -- "build()" --> E(((" ")))

[!visual-conversion] Typestate transitions ensure both host and port are set before building. Print UML state diagram (PDF 342, printed p. 336) recreated in Mermaid; the start dot and end bullseye are drawn as empty circles, state names and transition labels verbatim.

The diagram shows all valid paths through the builder. Starting from the initial state (no host, no port), either field can be set first. Both paths converge on the final state where build becomes available. The type system ensures code follows one of these paths; other sequences fail to compile.

Error messages from typestate violations can be cryptic. The compiler reports that build is not found for ConnectionBuilder<NoHost, HasPort>. Developers unfamiliar with the pattern might not understand why. Good documentation explaining the typestate design helps users interpret these errors. IDE support varies: some IDEs show available methods based on type parameters, others struggle with generic types.

The typestate pattern adds complexity. The type signatures become verbose, and the implementation requires multiple impl blocks for different state combinations. This cost is justified when configuration errors are common, when the consequences of misconfiguration are severe, or when the API is public and users benefit from compile-time enforcement. For internal builders with straightforward requirements, the standard pattern with runtime validation may suffice.

Singleton: the controversy and safe alternatives

The Singleton pattern ensures a class has exactly one instance, providing global access to it. In OOP languages, this typically involves a private constructor, a static instance field, and a static accessor method. The pattern is pervasive (loggers, configuration objects, connection pools) and controversial (global state, testing difficulties, hidden dependencies).

The controversy around singletons stems from their hidden coupling. Code that accesses a singleton depends on it without declaring that dependency. Function signatures lie: a function that reads configuration from a global singleton appears to take no configuration parameters. Testing such code requires global setup, potentially with cleanup between tests. Parallel test execution becomes hazardous when tests share and mutate global state.

Yet singletons persist because some resources genuinely have singleton semantics. A process has one standard output. A database connection pool exists once per application. Configuration typically loads once at startup. The question becomes how to provide singleton-like behavior without the associated problems.

Rust’s ownership system makes traditional singletons awkward. A mutable global requires synchronization for thread safety. The lazy initialization typical of singletons requires runtime checks. The global access point obscures dependencies, making code harder to reason about and test.

Several approaches address the singleton need in Rust, each with different trade-offs.

Compile-time initialization with const and static

For truly constant data, const values are inlined at compile time:

pub const MAX_CONNECTIONS: usize = 100;
pub const DEFAULT_TIMEOUT: Duration = Duration::from_secs(30);

Constants cannot be modified and have no runtime overhead. They suit configuration values known at compile time. The compiler may inline constants at use sites, eliminating even the memory read of accessing a global.

The limitation of const is its compile-time nature. Values must be computable during compilation, ruling out anything requiring runtime information (environment variables, file contents, command-line arguments). The types involved must implement the Copy trait or be references.

For data that needs a fixed memory location (for pointers or FFI), static provides a single instance:

pub static VERSION: &str = "1.0.0";

Mutable statics require unsafe because they introduce data races in multithreaded contexts. This is rarely the right choice.

The distinction between const and static reflects different memory models. A const is a compile-time value that may be duplicated at each use site. A static is a specific memory location that exists for the program’s lifetime. For most singleton use cases, this distinction does not matter. It becomes relevant for FFI, where C code expects a fixed address, or for large data where duplicating would waste memory.

Thread-local storage

When each thread needs its own instance, thread_local! provides thread-isolated storage without synchronization overhead. This pattern appears frequently in web servers, where request-specific data like request IDs, user context, or transaction scopes need to flow through the call stack without being passed as parameters.

The trade-off is straightforward: thread-local storage provides per-thread isolation without locks, at the cost of memory proportional to thread count. For data accessed frequently within a thread, the performance benefit is substantial. Each thread reads its own copy without any synchronization, achieving lock-free access patterns.

The following example shows a common pattern for request tracking:

thread_local! {
static REQUEST_ID: RefCell<Option<String>> = RefCell::new(None);
}
pub fn set_request_id(id: String) {
REQUEST_ID.with(|r| *r.borrow_mut() = Some(id));
}
pub fn get_request_id() -> Option<String> {
REQUEST_ID.with(|r| r.borrow().clone())
}

Each thread sees its own REQUEST_ID, eliminating synchronization needs. This pattern suits request-scoped data in web servers or per-thread caches.

The thread-local pattern trades memory for concurrency. Each thread maintains its own copy, consuming more memory than a shared singleton but avoiding synchronization overhead. For data accessed frequently within a request or operation, the performance benefit outweighs the memory cost. The pattern particularly suits scenarios where the data is set once per thread and read many times.

Lazy initialization with oncelock

The standard library’s OnceLock (and LazyLock) provide thread-safe lazy initialization. The value is computed once on first access and cached for subsequent calls. This pattern suits configuration that cannot be determined at compile time but remains constant once established.

The “lazy” aspect addresses startup cost. Eager initialization loads all configuration at program start, delaying the program’s availability. Lazy initialization defers each piece until first use, spreading the cost across time and avoiding work for unused components. The trade-off is unpredictable first-access latency, which matters for latency-sensitive applications.

The “once” aspect addresses thread safety. Multiple threads might access the singleton simultaneously, potentially triggering multiple initializations. OnceLock guarantees exactly one initialization, blocking concurrent first accesses until the single initialization completes. Subsequent accesses proceed without synchronization.

The following example demonstrates configuration loaded from environment variables:

use std::sync::OnceLock;
pub struct Config {
pub database_url: String,
pub log_level: String,
}
static CONFIG: OnceLock<Config> = OnceLock::new();
pub fn config() -> &'static Config {
CONFIG.get_or_init(|| {
Config {
database_url: std::env::var("DATABASE_URL")
.unwrap_or_else(|_| "localhost".to_string()),
log_level: std::env::var("LOG_LEVEL")
.unwrap_or_else(|_| "info".to_string()),
}
})
}

The initialization closure runs exactly once, even with concurrent first accesses. Subsequent calls return the cached value without synchronization overhead. This pattern suits configuration loaded from environment variables or files at startup.

The OnceLock type handles the synchronization internally. When multiple threads call get_or_init simultaneously, one thread executes the initialization while others wait. After initialization completes, all threads see the same value and no synchronization occurs on reads. This one-time synchronization cost amortizes across all subsequent accesses.

The pattern preserves the singleton’s key property (single instance) while addressing some objections. The initialization is lazy, avoiding startup cost for unused singletons. The accessor function returns a reference, making the dependency visible at call sites. However, the global nature remains: code still accesses the singleton through a global function rather than receiving it as a parameter.

Dependency injection as alternative

The most idiomatic Rust approach often avoids singletons entirely. Rather than global access, dependencies are passed explicitly through function parameters or struct fields. This approach, known as dependency injection, makes dependencies visible and controllable.

The principle is straightforward: code that needs a database connection receives it as a parameter rather than fetching it from a global. Code that needs configuration takes a Config parameter rather than accessing a static. Each function’s signature documents its dependencies. Testing provides mock implementations through the same parameters.

The cost of dependency injection is explicit plumbing. Dependencies must be passed through the call stack, sometimes through many layers. This verbosity can feel burdensome compared to global access.

The benefit is clarity: reading a function signature reveals its dependencies without examining the implementation.

The following example shows an application structured around explicit dependencies:

pub struct Application {
config: Config,
logger: Logger,
database: DatabasePool,
}
impl Application {
pub fn new(config: Config, logger: Logger, database: DatabasePool) -> Self {
Application { config, logger, database }
}
pub fn run(&self) {
self.logger.info("Starting application");
// Use self.config and self.database
}
}

Dependencies are explicit, visible in function signatures. Testing becomes straightforward: tests provide mock or stub implementations. The construction of the dependency graph happens at the application’s entry point, making the wiring visible and controllable.

This approach requires more explicit plumbing but results in code that is easier to understand, test, and modify. In my experience, the effort pays off in any codebase beyond trivial size.

The “composition root” pattern emerges from this approach. All dependencies are constructed and wired together at the application’s entry point (often the main function). The rest of the application receives dependencies through parameters and fields, never directly constructing them. This centralization makes the dependency structure visible and modifiable in one place.

Rust’s ownership system makes dependency injection natural. Dependencies are owned by the structs that need them, borrowed when temporary access suffices, or shared through Arc when multiple owners are necessary. The type system tracks these relationships, preventing use-after-free and data races that plague dependency injection in other languages.

For applications requiring runtime dependency resolution, crates like shaku provide dependency injection containers. These containers manage object lifetimes and dependency resolution, similar to Spring in Java or Autofac in C#. The trade-off is increased complexity in exchange for automatic wiring of complex dependency graphs.

Prototype through Clone

The Prototype pattern creates new objects by copying existing ones. Rather than constructing from scratch, a prototype instance is cloned, and the clone is modified as needed. This pattern suits objects with complex initialization where variations are minor.

The pattern addresses a specific problem: creating similar objects efficiently. Consider a document template with dozens of fields, most of which remain constant across documents. Reconstructing each document from scratch repeats the same initialization. Cloning a prototype and modifying the varying fields expresses the intent more clearly: this document is a variation of that template.

In OOP languages, the Prototype pattern often involves a clone method that subclasses override. The pattern enables polymorphic cloning: code holding a base class reference can clone without knowing the concrete type. This approach works around the fact that constructors are not inherited and cannot be called polymorphically.

Rust’s Clone trait provides the mechanism directly. Any type implementing Clone can be duplicated. The trait consists of a single method, clone, that returns a new instance with the same content as the original. The standard library provides the #[derive(Clone)] attribute for automatic implementation when all fields implement Clone.

The Clone trait bridges the gap between Rust’s move semantics and the need for duplication. By default, Rust moves values rather than copying them. A type implementing Clone opts into explicit duplication, making it possible to retain the original while working with a copy. This explicitness prevents accidental expensive copies while enabling intentional ones.

The following example demonstrates a document template that can be cloned and customized:

#[derive(Clone)]
pub struct DocumentTemplate {
pub title: String,
pub header: String,
pub footer: String,
pub styles: Vec<String>,
pub default_font: String,
}
impl DocumentTemplate {
pub fn corporate() -> Self {
DocumentTemplate {
title: String::new(),
header: "Company Name Inc.".to_string(),
footer: "Confidential".to_string(),
styles: vec!["corporate.css".to_string()],
default_font: "Arial".to_string(),
}
}
pub fn with_title(mut self, title: &str) -> Self {
self.title = title.to_string();
self
}
}

Creating variations starts from a prototype:

let template = DocumentTemplate::corporate();
let report = template.clone().with_title("Q4 Report");
let memo = template.clone().with_title("Meeting Notes");

The code expresses intent clearly: both report and memo derive from the corporate template, differing only in title. The .clone() call signals that a copy is being made, making the resource cost visible. The .with_title() call returns a modified instance through method chaining, a common Rust idiom for fluent configuration.

Note that the template itself remains unchanged. Each clone creates an independent copy that can be modified without affecting the original or other clones. This immutability of the prototype enables safe concurrent use: multiple threads can clone from the same template without synchronization.

The derive macro generates Clone implementations for structs where all fields implement Clone. For types requiring custom clone logic (deep copying referenced data, resetting unique identifiers), a manual implementation provides control.

The need for custom clone logic arises from semantic differences between identity and value. Some fields represent unique identifiers (UUIDs, database keys, sequence numbers) that should differ between original and clone. Other fields represent timestamps that should reflect when the clone was created, not when the original was created. The default derived Clone copies all fields bitwise, which may not preserve these semantic distinctions.

Implementing Clone manually gives precise control over what “copying” means for a type. The implementation decides which fields to copy, which to regenerate, and which to compute fresh. This flexibility enables the Prototype pattern to work correctly with types that have identity beyond their field values.

The following example demonstrates custom clone logic for a document with unique identity:

impl Clone for Document {
fn clone(&self) -> Self {
Document {
id: Uuid::new_v4(), // Generate new ID for clone
content: self.content.clone(),
created_at: Utc::now(), // Reset timestamp
}
}
}

The distinction between Clone (explicit, potentially expensive) and Copy (implicit, bitwise) matters here. Clone makes duplication visible in code, preventing accidental expensive copies. Types with heap allocations typically implement Clone but not Copy, requiring explicit .clone() calls.

This explicit/implicit distinction aligns with Rust’s philosophy of making costs visible. A type implementing Copy can be duplicated implicitly by assignment or passing to functions. The cost is typically trivial (a few bytes copied). A type implementing only Clone requires the explicit .clone() method, signaling to readers that a potentially expensive operation is occurring. When reviewing code, spotting clone() calls helps identify performance-sensitive areas.

The Prototype pattern in Rust thus has different ergonomics than in OOP languages. OOP clone methods often hide behind interfaces, their cost invisible at call sites. Rust’s explicit .clone() brings the copying into visibility. This visibility helps developers reason about performance without sacrificing the pattern’s benefits of easy object creation from templates.

Combining patterns

Real applications combine these patterns rather than using them in isolation. The patterns address different concerns: builders handle complex construction with many options, factories abstract over concrete types, prototypes simplify creating variations, and singletons manage shared resources. A single system might employ several patterns together, each contributing its specific benefit.

Consider a configuration system. Configuration objects often have many fields with sensible defaults. A builder provides a clean API for constructing them. The base configuration might be expensive to compute, read from files or environment variables. Lazy initialization ensures this cost is paid only when needed and only once. Different environments (production, staging, development) need variations of the base configuration. Cloning the base and modifying specific fields expresses these variations clearly.

First, the builder for complex configuration:

#[derive(Clone)]
pub struct AppConfig {
pub log_level: String,
pub max_connections: usize,
pub timeout_ms: u64,
pub retry_count: usize,
pub database_url: String,
}
pub struct AppConfigBuilder {
log_level: String,
max_connections: usize,
timeout_ms: u64,
retry_count: usize,
database_url: String,
}
impl AppConfigBuilder {
pub fn new() -> Self {
AppConfigBuilder {
log_level: "info".to_string(),
max_connections: 10,
timeout_ms: 30000,
retry_count: 3,
database_url: String::new(),
}
}
pub fn log_level(mut self, level: &str) -> Self {
self.log_level = level.to_string();
self
}
pub fn max_connections(mut self, count: usize) -> Self {
self.max_connections = count;
self
}
pub fn timeout_ms(mut self, ms: u64) -> Self {
self.timeout_ms = ms;
self
}
pub fn database_url(mut self, url: &str) -> Self {
self.database_url = url.to_string();
self
}
pub fn build(self) -> AppConfig {
AppConfig {
log_level: self.log_level,
max_connections: self.max_connections,
timeout_ms: self.timeout_ms,
retry_count: self.retry_count,
database_url: self.database_url,
}
}
}

Now the lazy singleton combined with prototype for variations:

use std::sync::OnceLock;
static BASE_CONFIG: OnceLock<AppConfig> = OnceLock::new();
pub fn base_config() -> &'static AppConfig {
BASE_CONFIG.get_or_init(|| {
AppConfigBuilder::new()
.log_level("info")
.max_connections(100)
.build()
})
}
pub fn config_for_environment(env: &str) -> AppConfig {
let mut config = base_config().clone();
match env {
"production" => {
config.log_level = "warn".to_string();
config.max_connections = 1000;
}
"development" => {
config.log_level = "debug".to_string();
}
_ => {}
}
config
}

The lazy initialization ensures the base config is computed once. Cloning creates independent copies for customization. The builder pattern simplified the initial construction. Each pattern addresses a specific concern without interference.

Notice how the patterns complement rather than compete. The builder provides a fluent construction API. The OnceLock provides thread-safe lazy initialization. The Clone trait enables efficient variation creation. Each pattern solves its problem without knowledge of the others. The composition happens in the application code, not in the pattern implementations.

This composability reflects good design. Patterns that require knowledge of other patterns create coupling that limits flexibility. Patterns that solve orthogonal problems independently can be mixed freely. Rust’s traits and ownership model naturally encourage this separation: each pattern is implemented through its own traits and types, with clear boundaries.

The combination also demonstrates how Rust’s features support pattern implementation. Associated functions provide named constructors. Traits define factory contracts. Generics enable type-safe builders. The standard library provides synchronization primitives for singletons. Clone enables prototyping. Each pattern finds natural expression in Rust’s feature set.

Patterns Discussed

This chapter covered the translation of creational patterns from OOP to Rust, showing how each pattern adapts to Rust’s different foundations. The absence of constructors and inheritance does not eliminate the need for these patterns; rather, it transforms their implementation while preserving their intent.

Rust’s lack of constructors and inheritance transforms creational patterns rather than eliminating them. Associated functions named new serve as conventional constructors, with additional named constructors for clarity. Fallible construction returns Result, making errors explicit.

The Factory pattern translates to traits when extensibility is needed, or to functions returning enums when the product set is closed. Abstract factories become traits with methods for each product in the family.

The Builder pattern accumulates configuration through chained method calls, producing complex objects in a readable way. The typestate variant encodes required fields in the type system, catching misconfiguration at compile time rather than runtime.

Singleton patterns in Rust typically use OnceLock for lazy initialization or explicit dependency injection. Thread-local storage serves per-thread singleton needs. The most idiomatic approach often passes dependencies explicitly, improving testability and clarity at the cost of more explicit wiring.

The Prototype pattern maps directly to Clone. Custom implementations control what copying means for types with identity or temporal fields.

These patterns demonstrate a recurring theme: Rust’s constraints (no constructors, no inheritance, explicit ownership) lead to designs that make intent and behavior more visible. The resulting code is often more explicit than OOP equivalents, and that explicitness aids understanding and maintenance.

The next chapter examines structural patterns, which address how objects compose to form larger structures. Where creational patterns focus on object creation, structural patterns focus on object composition. The same themes of trait-based abstraction and explicit ownership continue, but applied to different problems.