Skip to content

Chapter 2 of 8

Structures, Enums, and Pattern Matching

Rust offers two principal ways to compose custom data types: structs and enums. A struct groups related fields together, and Rust supports three flavors — named-field structs, tuple structs, and unit structs — so you can pick the form that best fits your data. Behavior is attached separately using an `impl` block, where methods take `&self`, `&mut self`, or `self` as their first parameter to declare how they interact with the receiver.

Enums declare a type whose values are one of several named variants, and each variant can carry its own data. A shape might be either a `Circle(f64)` carrying a radius or a `Rectangle { width: f64, height: f64 }` carrying its dimensions. This is a true sum type: every value encodes both which case it belongs to and the data for that case, which makes enums far more expressive than their counterparts in most other languages.

Pattern matching with `match` is the natural companion to these types. A `match` expression destructures a value and branches on its shape, while the compiler enforces exhaustiveness: every variant must be handled, or the program will not compile. This guarantee eliminates the entire class of bugs where a developer forgets to consider one branch, and it encourages designers to make the state space of a type fully explicit.

For situations where a full `match` would be overkill, Rust offers `if let` to handle a single interesting pattern and a `while let` loop that continues as long as a pattern keeps matching. Both are syntactic sugar for a `match` with one meaningful arm and a wildcard, and they let you write tighter code when the alternatives are not interesting enough to enumerate.

All chapters
  1. 1Foundations of Rust Memory Safety
  2. 2Structures, Enums, and Pattern Matching
  3. 3Error Handling with Option and Result
  4. 4Traits, Generics, and Polymorphism
  5. 5Iterators, Closures, and Functional Patterns
  6. 6Modules, Crates, Cargo, and Testing
  7. 7Concurrency in Rust
  8. 8Smart Pointers and Unsafe Rust

Drill it

Reading is not remembering. These come from the Rust Programming deck:

Q

What is Rust?

Rust is a systems programming language focused on safety, speed, and concurrency. It achieves memory safety without a garbage collector through its ownership sy...

Q

What is ownership in Rust?

Ownership is Rust's core memory management concept. Each value has exactly one owner, and when the owner goes out of scope, the value is dropped (freed). This p...

Q

What are the three ownership rules in Rust?

Each value in Rust has a single ownerThere can only be one owner at a timeWhen the owner goes out of scope, the value is dropped

Q

What is borrowing in Rust?

Borrowing lets you reference a value without taking ownership. You create a reference with &. The original owner retains ownership while the borrower can re...