Structs, Enums, and the Death of Null
local graph
Chapter 3 — Structs, Enums, and the Death of Null
Section titled “Chapter 3 — Structs, Enums, and the Death of Null”Ex nihilo nihil fit. (Nothing comes from nothing.)
Object-oriented languages combine data and behavior in classes, creating objects that encapsulate state and expose methods. Rust separates these concerns. Structs define data layout. Enums define variants. Implementations attach behavior to both, but the data definitions stand independent. With ownership and borrowing providing the safety foundation, this separation enables patterns that class-based hierarchies cannot express.
This separation initially feels like a step backward to developers trained in object-oriented design. The encapsulation of data with behavior seems fundamental to managing complexity. A class bundles what a thing is with what it can do. Yet the separation offers advantages that become apparent as designs evolve. Data structures can be defined once and extended with behavior from multiple sources. Pattern matching enables exhaustive handling of all cases. Most significantly, the absence of null (replaced by explicit types that encode presence or absence) eliminates an entire category of runtime errors.
Structs as data containers
A Rust struct defines a collection of named fields with specified types. The simplest form resembles a C struct or a Java record: a User struct might contain a username field of type String, an email field also of type String, an active field of type bool, and a sign_in_count field of type u64. Unlike a Java class, the struct defines only data layout. There are no constructors in the struct definition, no methods, no inheritance relationships. The struct is a product type: a User consists of a username and an email and an active flag and a sign-in count.
Creating an instance uses a syntax that names each field and provides its value. All fields must be initialized; there is no default initialization to null or zero. The compiler rejects any attempt to create a struct with missing fields. This eliminates the partially initialized object problem that plagues object-oriented languages, where constructors must carefully ensure that all fields are set before the object becomes visible to other code.
Consider a Java class where the constructor allows this to escape before initialization completes:
Java: partially initialized object escapes
class User { private String name; private EmailService emailService;
public User(String name) { this.name = name; this.emailService = new EmailService(this); // 'this' escapes before fully initialized // What if an exception occurs here? Object already leaked. }}The EmailService receives a reference to the User before the constructor finishes. If subsequent initialization fails, the EmailService holds a reference to a partially constructed object. Other code might access fields that were never set.
Rust’s struct construction eliminates this problem:
struct User { name: String, email_service: EmailService,}
impl User { fn new(name: String) -> Self { // Cannot return partial User; all fields required User { name, email_service: EmailService::new(), // No 'self' available until struct complete } }}There is no self to leak during construction. The struct literal syntax requires all fields to be specified before the value exists. The fully constructed struct is returned as a unit. No code can observe a User between the start and end of its construction because there is no intermediate state to observe.
Field access uses dot notation, as in most languages. Mutation requires the binding to be mutable; the mut keyword on the binding allows modification of any field. Note that mutability is all-or-nothing for a struct instance. You cannot have some fields mutable and others immutable (with exceptions for interior mutability patterns discussed in later chapters). This differs from object-oriented languages where individual fields can be declared final or readonly while others remain mutable. The constraint simplifies reasoning: if a binding is mutable, any part of it might change; if immutable, no part will change.
Tuple structs and unit structs
Rust provides two additional struct forms for specialized use cases. Tuple structs have fields accessed by position rather than name. A Point struct might contain two f64 values accessed as .0 and .1, while a Color struct might contain three u8 values. Tuple structs are useful when the field names would add little information (x and y for a point are obvious from context) or when creating distinct types from existing types.
The type distinction matters more than it first appears. A Color containing three bytes and a Point containing three coordinates might have similar underlying representations, but the type system treats them as completely different types. Passing a Color where a Point is expected produces a compile error. This prevents the category of bugs where values are confused because they happen to have the same shape. In languages with structural typing or weak type systems, two unrelated concepts with similar representations might be accidentally interchanged. Rust’s nominal typing ensures that types are distinguished by their names, not their internal structure.
Unit structs have no fields at all. They are useful as marker types for implementing traits or for type-level programming where the type itself carries meaning but no runtime data is needed. A unit struct occupies zero bytes; it exists purely as a compile-time construct. This enables patterns where type information guides behavior without runtime overhead.
Adding behavior with impl blocks
Behavior attaches to structs through implementation blocks, written with the impl keyword followed by the type name. Methods and associated functions are defined within the block, separate from the data definition. Methods take a form of self as their first parameter: &self for immutable access, &mut self for mutable access, or self for consuming ownership.
The separation of data definition from behavior definition has significant implications. Methods are not part of the struct’s identity.
The same struct can have multiple impl blocks in different parts of the code. Other crates can add behavior to your types through traits (covered in the next chapter). The relationship between data and behavior is explicit and extensible, not fixed at the point of struct definition.
Associated functions that do not take self serve the role of constructors or static methods in object-oriented languages. Rust has no special constructor syntax; any function that returns an instance of the type can serve as a constructor. This flexibility allows multiple constructor-like functions with descriptive names. A Rectangle might have a new function taking width and height, a square function taking a single size, and a from_corners function taking two points. Each name communicates intent; there is no confusion about which overloaded constructor is being called.
The following diagram illustrates the relationship between structs, impl blocks, and traits:
graph TD
subgraph DD["Data Definition"]
S["struct Rectangle"]
end
subgraph BH["Behavior"]
I1["impl Rectangle<br/>(inherent methods)"]
I2["impl Display for Rectangle"]
I3["impl Debug for Rectangle"]
end
S --> I1
S --> I2
S --> I3
[!visual-conversion] Separation of data definition from behavior in Rust. Print diagram (PDF 111, printed p. 109) recreated in Mermaid; labels verbatim.
Visibility and encapsulation
Rust’s visibility rules provide encapsulation without the class-based access modifiers of object-oriented languages. By default, struct fields are private to the module where the struct is defined. The pub keyword makes items public. This applies at the module level, not the class level: all code within the same module can access private fields, regardless of which type they belong to.
When a struct has private fields, code outside the module cannot construct it directly because it cannot set the private fields. This pattern forces the use of constructor functions, which can enforce invariants. The struct might have a public constructor function that validates inputs before creating an instance, ensuring that all instances satisfy certain constraints. Outside code cannot bypass these constraints by constructing the struct directly.
This achieves encapsulation similar to object-oriented private fields with getter methods, but through module-level visibility rather than class-level access modifiers. The granularity differs (module rather than class), but the goal of hiding implementation details remains achievable. In practice, the module as the unit of encapsulation often aligns better with actual code organization than the class as the unit of encapsulation.
Enums as algebraic data types
Rust enums are far more powerful than their counterparts in Java (pre-sealed classes) or C/C++. A Rust enum is a sum type: a value of the enum type is one of its variants, not a combination. Each variant can carry different data, including no data at all.
Consider modeling a message in a chat application. One variant might be Quit, carrying no data. Another might be Move, carrying x and y coordinates. A third might be Write, carrying a String with the message text. A fourth might be ChangeColor, carrying three bytes for RGB values. A Message value is one of these four possibilities, never more than one, never none.
The enum itself takes enough space for its largest variant plus a discriminant to identify which variant is present. The compiler optimizes this layout, and in many cases (such as Option around a pointer) can eliminate the discriminant entirely through null pointer optimization.
This differs fundamentally from Java enums, which are essentially a fixed set of singleton instances. Java enum values are objects of the enum class; they all have the same fields and methods. Rust enum variants can contain different amounts and types of data. They model the kind of variation that Java developers typically handle through class hierarchies: a base Message interface with QuitMessage, MoveMessage, WriteMessage, and ChangeColorMessage subclasses.
The Rust approach is more concise and more type-safe. Adding a new variant to an enum is a single line. Adding a new subclass in Java involves creating a new file, extending the base class, implementing abstract methods, and ensuring the class is properly registered with any factory or dispatch mechanisms. More importantly, Rust’s pattern matching ensures exhaustive handling: when you match on an enum, the compiler verifies that you handle every variant. Adding a variant causes compilation failures everywhere the enum is matched without handling the new case. In Java, the compiler provides no such guarantee for class hierarchies.
Modeling state with enums
Enums excel at modeling state machines and domain concepts where a value can be in one of several distinct states. Consider a network connection that might be disconnected, connecting (with a retry attempt count), connected (with a session identifier), or failed (with an error message and retry time). Each state carries exactly the data relevant to that state. A disconnected connection needs no additional information. A connecting state tracks retry attempts. A connected state holds the session identifier. A failed state records the error and scheduled retry time.
This approach makes invalid states unrepresentable. There is no possibility of a connection that is simultaneously connected and has an error message from a failure. There is no null session_id that might be checked or forgotten. The type system ensures that code handling a Connected variant has access to session_id, and code handling a Failed variant has access to error information. You cannot accidentally access the wrong data because the pattern matching that extracts the variant also provides access to exactly the data that variant contains.
Compare this to the object-oriented approach of a single Connection class with nullable fields. Such a class might have a status field indicating the current state, plus nullable fields for attempt count, session ID, error message, and retry time. This representation allows nonsensical states: a connected connection with a non-null error, a failed connection with a session_id, a disconnected connection with a retry attempt count. Defensive programming and careful documentation attempt to prevent these states, but the type system provides no assistance. In Rust, the enum structure makes such states impossible to construct.
The principle extends beyond simple state machines. Domain modeling benefits greatly from sum types. A payment might be Pending, Authorized, Captured, Refunded, or Failed, with each state carrying different associated data. An HTTP response might be Success with a body, Redirect with a location, ClientError with a status code and message, or ServerError with diagnostic information. The pattern appears wherever values can be in one of several distinct states with state-specific data.
The Option type: absence made explicit
Chapter 1 introduced Option<T> as one of Rust’s key advantages
over languages with null references. This section explores how to
work with Option effectively.
The most important enum in Rust is Option<T>, defined in the
standard library. Option has two variants: Some, which contains a
value of type T, and None, which contains nothing. This type
represents the presence or absence of a value.
Unlike null references in object-oriented languages, Option makes
absence explicit in the type system. A function returning
Option<User> clearly indicates that it might not produce a User. A
function returning User will definitely produce a User (or not return
at all, perhaps by panicking). The type signature communicates the
possibility of absence, and callers must handle it.
In Java, C#, and C++, any reference might be null. The type system does not distinguish between a User reference that might be null and one that definitely points to a User. Callers might forget to check. Callers might check sometimes but not always. Static analysis tools can help, but they operate outside the type system, and their warnings are often ignored or overridden. Null pointer exceptions remain among the most common runtime errors in production systems despite decades of experience with the problem.
Rust eliminates this category of errors entirely. If a function might not return a value, it returns Option. Callers must handle the None case, either through pattern matching, through combinator methods like map and unwrap_or, or through early returns with the question mark operator. There is no way to accidentally use a User that does not exist because you cannot access the User inside an Option without first checking whether the Option is Some.
The Option type provides numerous convenience methods for common operations. The map method transforms the contained value if present. The unwrap_or method provides a default when the Option is None. The and_then method chains operations that might fail. The ? operator propagates None to the caller when used in a function that returns Option. These methods compose naturally, enabling concise expression of operations on values that might be absent.
Consider retrieving a user’s city from a nested optional structure. In Java, defensive null checking produces verbose code:
// Java: defensive null checkingpublic String getUserCity(User user) { if (user == null) return "Unknown"; Address address = user.getAddress(); if (address == null) return "Unknown"; String city = address.getCity(); return city != null ? city : "Unknown";}Each level requires explicit null checks. Missing any check risks a NullPointerException. The actual business logic (getting the city from an address from a user) is buried in defensive boilerplate.
Rust’s Option combinators express the same logic concisely:
fn get_user_city(user: Option<&User>) -> &str { user.and_then(|u| u.address.as_ref()) .and_then(|a| a.city.as_ref()) .map(|s| s.as_str()) .unwrap_or("Unknown")}Each and_then unwraps the Option if present and applies the closure, or propagates None if absent. The chain expresses the happy path (user exists, address exists, city exists), with None handling implicit. The final unwrap_or provides the default.
For functions returning Option, the ? operator provides even more concise propagation:
fn get_user_city_opt(user: Option<&User>) -> Option<&str> { Some(user?.address.as_ref()?.city.as_ref()?.as_str())}Each ? returns early with None if the preceding expression is None. The function body reads as “get the user’s address’s city,” with the question marks marking each point where absence might occur.
The unwrap and expect methods extract the contained value but panic if the Option is None. These methods are appropriate when absence represents a programming error rather than an expected condition. If a configuration value must be present for the program to function, unwrapping with a descriptive message is appropriate. If a user-provided value might be missing, pattern matching or combinators provide graceful handling.
The discipline of working with Option changes how you think about data. In object-oriented languages, the question “can this be null?” requires examining documentation, reading code, or discovering the answer through runtime failures. In Rust, the type tells you. Option might be absent. User will be present. This clarity propagates through the entire codebase, making absence visible at every level of the call stack.
The Result type: errors made explicit
Where Option models presence or absence, Result models success or failure. Chapter 1 noted how this differs from exception-based error handling; this section examines Result’s mechanics.
Result has two variants: Ok, which contains a success value of type T, and Err, which contains an error value of type E. A function returning Result<User, DatabaseError> might succeed and return a User, or fail and return a DatabaseError explaining why.
Like Option, Result forces callers to acknowledge both possibilities. The type signature advertises that the function can fail and what kind of error it might produce. Callers must handle the error case, either by pattern matching, by propagating with the question mark operator, or by using combinator methods.
This contrasts with exceptions in object-oriented languages. Java’s checked exceptions attempted to make error handling explicit, requiring callers to catch or declare exceptions. But checked exceptions proved cumbersome, and many libraries switched to unchecked exceptions that can be thrown from anywhere and caught (or not) anywhere else. C# never required exception handling, treating all exceptions as unchecked. The result in both cases is that error paths are invisible in method signatures. A method that claims to return a User might instead throw a DatabaseException, a NetworkException, or any number of other failures. Callers discover these possibilities through documentation (if it exists), testing (if it covers the failure paths), or production incidents (if neither of the above).
Rust’s Result type makes errors part of the function signature, visible to callers and enforced by the compiler. The question mark operator provides concise propagation: if a Result is Err, the error is returned from the current function; if Ok, the contained value is extracted and execution continues. This is as concise as exception propagation but with explicit type information.
The following diagram contrasts nullable references with Option and Result:
graph LR
subgraph NR["Nullable"]
N1["Reference or null"] -.-> N2["Caller may forget to check"] -.-> N3["Runtime exception on access"]
end
subgraph OP["Option T"]
O1["Some value or None"] --> O2["Compiler requires handling"] --> O3["No runtime surprise"]
end
subgraph RS["Result T E"]
R1["Ok value or Err error"] --> R2["Error type in signature"] --> R3["Explicit error path"]
end
[!visual-conversion] Nullable references vs. Option and Result: compile-time enforcement vs. runtime surprises. Print diagram (PDF 119, printed p. 117) of three stacked frames, recreated in Mermaid. The print shows the frame titles as “Option T” and “Result T E” (angle brackets missing in the original artwork) and the first frame’s title is partly hidden (“Nullable” + an obscured second line); transcribed as printed. The edges in the Nullable row are dotted in print.
Error handling with Result is covered extensively in Chapter 8. For now, the key insight is that Result makes errors part of the type signature, visible to callers and enforced by the compiler.
Pattern matching as control flow
Pattern matching is Rust’s mechanism for examining the structure of values and binding variables to their components. The match expression is the most general form. Each arm of a match specifies a pattern and an expression to evaluate when the pattern matches.
Patterns can bind variables, destructure complex types, and include guards for additional conditions.
Match expressions must be exhaustive. The compiler verifies that all possible variants are handled. Adding a new variant to an enum causes compilation failures everywhere that enum is matched without handling the new case. This eliminates the risk of unhandled cases that can plague switch statements in other languages, where a missing case silently falls through or triggers a default that might be inappropriate for the new variant.
The exhaustiveness requirement transforms maintenance from a discipline problem into a compiler-enforced guarantee. When you add a variant to an enum, you do not need to search the codebase for places that handle the enum. The compiler does that search for you and refuses to compile until every location handles the new variant. This is particularly valuable in large codebases where the original author of an enum might not know all the places it is used.
Match guards and pattern composition
Patterns can include guards, additional conditions that must be true for the pattern to match. A match arm might handle Move variants, but only when the x and y coordinates are both positive. The guard is evaluated after the pattern matches structurally but before the arm’s expression executes. This allows finer-grained discrimination than structural patterns alone.
The underscore pattern matches anything without binding a variable. It serves as a catch-all for uninteresting cases, or as a placeholder in patterns where some components are irrelevant. A match arm handling all non-Move messages might use underscore for the entire value, or a match arm handling Move might use underscore for the y coordinate if only x matters.
Patterns can also specify how values are bound. The ref keyword creates a reference to the matched value rather than moving it. Modern Rust often infers binding modes from context, but explicit annotation remains useful for clarity in complex patterns.
Multiple patterns can be combined with the pipe operator to handle several cases with the same code. Range patterns work for characters and integers, making match expressions natural for classifying values into categories.
Destructuring in patterns
Pattern matching extends beyond simple variant selection to destructuring complex nested structures. Structs, tuples, and enums can all be taken apart in patterns, binding their components to variables for use in the match arm. This capability enables extracting exactly the data needed without intermediate steps.
struct Point { x: i32, y: i32 }
enum Message { Move { x: i32, y: i32 }, Color(u8, u8, u8),}
fn demonstrate_destructuring() { // Struct destructuring let p = Point { x: 10, y: 20 }; let Point { x, y } = p; // Bind x and y to field values let Point { x: a, y: b } = p; // Rename while destructuring let Point { x, .. } = p; // Ignore some fields with ..
// Tuple destructuring let tuple = (1, "hello", 3.14); let (a, b, c) = tuple; // Bind all elements let (first, ..) = tuple; // Bind first, ignore rest
// Enum destructuring in match let msg = Message::Move { x: 10, y: 20 }; match msg { Message::Move { x, y } => println!("Move to {}, {}", x, y), Message::Color(r, g, b) => println!("RGB: {}, {}, {}", r, g, b), }
// Nested destructuring let nested = ((1, 2), Point { x: 3, y: 4 }); let ((a, b), Point { x, y }) = nested;
// Destructuring in function parameters fn print_point(&Point { x, y }: &Point) { println!("({}, {})", x, y); }}The @ binding operator captures a value while simultaneously testing it against a pattern. This proves useful when you need both the matched value and some structural information about it:
fn classify_number(num: Option<i32>) { match num { Some(n @ 1..=50) => println!("Small number: {}", n), Some(n @ 51..=100) => println!("Medium number: {}", n), Some(n) => println!("Large number: {}", n), None => println!("No number"), }}The @ operator binds the matched value to n while also verifying it falls within the specified range. Without @, you would need a guard clause (Some (n) if n >= 1 && n <= 50) which cannot prove to the compiler that n is bounded, or separate matches that duplicate logic.
Convenient pattern matching forms
When only one variant is interesting, if let provides a more concise alternative to match. The pattern appears after if let, and if it matches, the block executes with any bound variables in scope. This is equivalent to a match with two arms: one for the interesting case and a catch-all that does nothing. The if let form is preferable when the non-matching case requires no action.
Similarly, while let loops while a pattern matches. Popping elements from a stack until it is empty, for instance, naturally uses while let with the pattern matching Some around the popped value. When pop returns None, the pattern fails to match and the loop exits.
The let-else construct combines pattern matching with early returns. If the pattern matches, the bound variables are available in subsequent code. If the pattern does not match, the else block must diverge (return, break, continue, or panic). This pattern reduces nesting compared to nested if-let or match expressions, particularly when validating preconditions at the start of a function.
fn process_config(config: Option<&Config>) -> Result<(), ConfigError> { // let-else: destructure or return early let Some(config) = config else { return Err(ConfigError::Missing); };
let Some(database) = &config.database else { return Err(ConfigError::NoDatabase); };
// Now config and database are available directly, no unwrapping needed connect(database)?; Ok(())}The let-else pattern keeps the happy path at the left margin while handling errors inline. Compare this to nested if-let expressions, which push the main logic rightward with each check.
If-let chains extend this ergonomics further by combining pattern matching with boolean conditions in a single expression:
fn check_credentials(user: Option<&User>, required_role: &str) -> bool { if let Some(user) = user && user.is_active && user.roles.contains(&required_role.to_string()) { true } else { false }}The chain evaluates left to right, short-circuiting on the first failure. The pattern must match and all conditions must be true for the block to execute. This combines what would otherwise require nested if-let expressions or a match with guards.
Matching on references
When matching on a reference, patterns must account for the reference. Match ergonomics, a feature added to make pattern matching on references more convenient, automatically adjusts patterns based on the reference type of the value being matched. When matching on &Option, the variable bound inside Some is automatically a reference to the User, not an owned User. This reduces the need for explicit dereferencing in common cases.
Understanding match ergonomics becomes important when the default behavior is not what you want. Sometimes you want to take ownership of the contained value, or sometimes you want to create a reference where the default would be a copy. Explicit binding modes with ref and ref mut override the automatic behavior when needed.
Putting it together: a domain model
Consider modeling a simple e-commerce order system. In object-oriented design, this might involve an Order base class with Pending, Shipped, and Delivered subclasses, or a single Order class with a status field and nullable shipping and delivery dates.
The Rust approach uses structs for data and enums for states. The order ID and customer ID might be tuple structs wrapping u64, providing type safety so that passing a customer ID where an order ID is expected produces a compile error (even though both are ultimately unsigned 64-bit integers). This type safety costs nothing at runtime: the tuple struct is a zero-cost abstraction that exists only in the type system.
Order items form a struct with product ID, quantity, and price. Shipping information forms another struct with carrier, tracking number, and ship date. Delivery information includes the delivery date and an optional signature. Each struct captures exactly the data relevant to its concept, with no extra fields that might be null or unused in certain contexts.
The order status becomes an enum with variants for Pending (no associated data), Shipped (containing shipping information), Delivered (containing both shipping and delivery information), and Cancelled (containing a reason string). The order itself is a struct containing the IDs, a vector of items, and the status.
The following code shows the complete implementation:
use chrono::{DateTime, Utc};
// Type-safe IDs using newtype pattern#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]pub struct OrderId(u64);
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]pub struct CustomerId(u64);
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]pub struct ProductId(u64);
// Order item with all fields#[derive(Debug, Clone)]pub struct OrderItem { pub product_id: ProductId, pub quantity: u32, pub unit_price: u64, // cents to avoid floating point}
// Shipping and delivery info#[derive(Debug, Clone)]pub struct ShippingInfo { pub carrier: String, pub tracking_number: String, pub shipped_at: DateTime<Utc>,}
#[derive(Debug, Clone)]pub struct DeliveryInfo { pub delivered_at: DateTime<Utc>, pub signature: Option<String>,}
// Order status as enum with associated data#[derive(Debug, Clone)]pub enum OrderStatus { Pending, Shipped(ShippingInfo), Delivered { shipping: ShippingInfo, delivery: DeliveryInfo, }, Cancelled { reason: String },}
#[derive(Debug, Clone)]pub struct Order { pub id: OrderId, pub customer_id: CustomerId, pub items: Vec<OrderItem>, pub status: OrderStatus,}
impl Order { pub fn new(id: OrderId, customer_id: CustomerId, items: Vec<OrderItem>) -> Self { Order { id, customer_id, items, status: OrderStatus::Pending, } }
pub fn total(&self) -> u64 { self.items.iter() .map(|item| item.unit_price * item.quantity as u64) .sum() }
pub fn ship(&mut self, info: ShippingInfo) -> Result<(), &'static str> { match &self.status { OrderStatus::Pending => { self.status = OrderStatus::Shipped(info); Ok(()) } _ => Err("Can only ship pending orders"), } } pub fn deliver(&mut self, delivery: DeliveryInfo) -> Result<(), &'static str> { match &self.status { OrderStatus::Shipped(shipping) => { self.status = OrderStatus::Delivered { shipping: shipping.clone(), delivery, }; Ok(()) } _ => Err("Can only deliver shipped orders"), } }
pub fn tracking_number(&self) -> Option<&str> { match &self.status { OrderStatus::Shipped(info) => Some(&info.tracking_number), OrderStatus::Delivered { shipping, .. } => Some(&shipping.tracking_number), _ => None, } }}Behavior attaches through impl blocks. A constructor function creates new orders in the Pending state. A total calculation method iterates over items to compute the order total. Ship and deliver methods transition the order through states, using pattern matching to verify that the current state permits the transition. A tracking number accessor returns Option, since only shipped and delivered orders have tracking numbers.
The design demonstrates several Rust idioms in concert. Tuple structs create distinct types from the same underlying data, preventing accidental confusion between IDs. Enums with associated data model state machines where each state carries exactly the information relevant to that state. Option makes nullable concepts explicit, forcing callers to handle the case where tracking numbers are not available.
Pattern matching ensures exhaustive handling of all states, with the compiler rejecting code that does not account for newly added states.
The type system enforces domain rules that would otherwise require runtime checks or careful documentation. An order cannot be delivered without first being shipped because the Delivered variant requires shipping information that can only come from the Shipped state. An order cannot have a tracking number in the Pending state because tracking numbers exist only within the Shipped and Delivered variants. These constraints are structural, not behavioral: they arise from how the types are defined, not from how the code is written.
Extending this design is straightforward. Adding a new status like PartiallyShipped requires adding a variant to the enum. The compiler then identifies every place that matches on OrderStatus, requiring each location to handle the new variant. No manual search is needed; no test coverage is required to find the missing cases. The type system does the work that would otherwise require careful discipline and comprehensive testing.
What You Have Learned
Rust’s data modeling separates data layout (structs and enums) from behavior (impl blocks). Structs define product types where instances contain all fields. Enums define sum types where instances are one of several variants, each potentially carrying different data. This separation, initially unfamiliar to object-oriented developers, enables flexible composition and extension that class-based inheritance cannot match.
The Option type replaces null references, making absence explicit in the type system. The Result type represents operations that might fail, with error information encoded in the type signature. Both types leverage pattern matching to ensure callers handle all cases. The compiler becomes an ally, catching missing cases and enforcing complete handling.
Pattern matching through match expressions, if let, while let, and let-else provides exhaustive, type-safe handling of structured data. The compiler verifies that all variants are covered, eliminating unhandled cases that cause runtime failures in other languages. Adding a variant to an enum triggers compilation failures at every incomplete match, ensuring consistent updates throughout the codebase.
Visibility at the module level provides encapsulation without class-based access modifiers. Private fields force the use of constructor functions, enabling invariant enforcement. The module as the unit of encapsulation often aligns better with actual code organization than the class.
Tuple structs enable type-safe wrappers around primitive types, preventing the confusion bugs that arise when multiple values share the same representation. Unit structs serve as markers for type-level programming. These specialized struct forms complement the standard named-field struct.
The domain modeling example demonstrated how these concepts combine in practice. Type safety through tuple structs, state machines through enums, explicit absence through Option, and exhaustive handling through pattern matching work together to encode domain rules in the type system rather than in runtime checks or documentation.
The next chapter introduces traits, Rust’s mechanism for defining shared behavior across types. Traits enable polymorphism without inheritance, providing the flexibility of interfaces with additional capabilities that object-oriented interfaces cannot match.