Structs, Enums & Pattern Matching

Defining data in Rust — structs and impl blocks, methods and associated functions, enums with data (algebraic data types), Option instead of null, exhaustive match, if let, let-else, and modelling state with types.

Intermediate 2 min readLesson 4 of 9

Rust's data modelling has two pillars: structs (a value with several fields — "and") and enums (a value that is one of several variants, each possibly carrying data — "or"). Combined with exhaustive pattern matching, they let you make illegal states unrepresentable.

Structs

Rust
#[derive(Debug, Clone, PartialEq)]          // auto-implement common traits
struct User {
    username: String,
    email: String,
    active: bool,
    sign_in_count: u64,
}

let mut user = User {
    username: String::from("ada"),
    email: String::from("ada@example.com"),
    active: true,
    sign_in_count: 1,
};
user.sign_in_count += 1;                     // the whole instance must be mut

let user2 = User { email: String::from("x@example.com"), ..user };   // struct update syntax (moves the rest)

struct Point(f64, f64);                      // tuple struct
struct Meters(f64);                          // newtype: distinct type, zero cost
struct Marker;                               // unit struct
println!("{user:?}");                        // Debug printing

impl blocks: methods and associated functions

Rust
impl User {
    // Associated function (no self) — often a constructor
    fn new(username: &str, email: &str) -> Self {
        Self { username: username.into(), email: email.into(), active: true, sign_in_count: 0 }
    }

    fn display_name(&self) -> &str {         // borrow immutably
        &self.username
    }

    fn deactivate(&mut self) {               // borrow mutably
        self.active = false;
    }

    fn into_email(self) -> String {          // take ownership (consumes the User)
        self.email
    }
}

let mut u = User::new("ada", "ada@example.com");
u.deactivate();                               // auto-borrows &mut u

The receiver type documents intent: &self reads, &mut self modifies, self consumes.

Enums with data

Rust enums are sum types: each variant can hold different data.

Rust
enum Shape {
    Circle { radius: f64 },
    Rectangle { width: f64, height: f64 },
    Triangle(f64, f64, f64),
}

impl Shape {
    fn area(&self) -> f64 {
        match self {
            Shape::Circle { radius } => std::f64::consts::PI * radius * radius,
            Shape::Rectangle { width, height } => width * height,
            Shape::Triangle(a, b, c) => {
                let s = (a + b + c) / 2.0;
                (s * (s - a) * (s - b) * (s - c)).sqrt()
            }
        }
    }
}

Compare with Java sealed interfaces + records or TypeScript discriminated unions — the same idea, built into the language from the start (Modern Java).

Option: no null

Rust has no null. A value that may be absent has type Option<T>:

Rust
enum Option<T> {
    Some(T),
    None,
}

You can't use an Option<User> as a User — the compiler forces you to handle None:

Rust
fn find_user(id: u32) -> Option<User> { /* ... */ None }

match find_user(42) {
    Some(user) => println!("found {}", user.username),
    None => println!("no such user"),
}

let name = find_user(42).map(|u| u.username).unwrap_or_else(|| "guest".to_string());
let count = maybe_count.unwrap_or(0);
if let Some(u) = find_user(7) { greet(&u); }

Tony Hoare called null references his "billion-dollar mistake"; Option eliminates null pointer exceptions entirely. Its sibling Result<T, E> handles errors (Error handling).

Pattern matching

match compares a value against patterns, binds variables, and must be exhaustive — forget a case and it won't compile.

Rust
match value {
    0 => "zero",
    1 | 2 => "small",
    3..=9 => "single digit",
    n if n < 0 => "negative",            // guard
    _ => "large",                        // wildcard
}

// Destructuring structs, tuples, nested enums
match point {
    Point { x: 0, y } => println!("on the y axis at {y}"),
    Point { x, y: 0 } => println!("on the x axis at {x}"),
    Point { x, y } => println!("({x}, {y})"),
}

match msg {
    Message::Move { x, y: 0 } => horizontal(x),
    Message::Write(text) if text.is_empty() => {}
    Message::Write(text) => print(&text),
    Message::ChangeColor(r, g, b) => recolor(r, g, b),
    Message::Quit => quit(),
}

// Binding with @
match age {
    n @ 13..=19 => println!("teen aged {n}"),
    _ => {}
}

// Slice patterns
match items.as_slice() {
    [] => "empty",
    [only] => "one",
    [first, .., last] => "many",
}

Shorter forms

Rust
if let Some(config) = load_config() {
    apply(config);
}

let Some(user) = find_user(id) else {       // let-else: bind or diverge
    return Err("not found");
};

while let Some(job) = queue.pop() {
    run(job);
}

let is_admin = matches!(role, Role::Admin | Role::Owner);

Making illegal states unrepresentable

Compare two ways to model a network connection:

Rust
// Fragile: which fields are valid depends on the flags
struct Connection {
    connected: bool,
    session_id: Option<String>,
    retry_count: u32,
    error: Option<String>,
}

// Robust: each state carries exactly the data that makes sense in it
enum Connection {
    Disconnected,
    Connecting { attempt: u32 },
    Connected { session_id: String },
    Failed { error: String },
}

fn send(conn: &Connection, data: &[u8]) -> Result<(), String> {
    match conn {
        Connection::Connected { session_id } => transmit(session_id, data),
        _ => Err("not connected".into()),
    }
}

A Connected without a session ID can't exist; the compiler forces every state to be handled. This typestate thinking is one of Rust's biggest practical benefits — and it carries over to TypeScript, Kotlin, Swift and modern Java.

Memory layout

Enums are stored as a tag (which variant) plus space for the largest variant. Rust optimises niches: Option<&T> and Option<Box<T>> are the same size as a pointer, because a null pointer can represent None — so Option is free.

Key takeaways
  • Structs group fields; impl blocks add methods (&self, &mut self, self) and associated functions.
  • Enums are sum types whose variants carry data.
  • Option replaces null; the compiler forces you to handle None.
  • match is exhaustive, supports destructuring, ranges, guards and bindings; if let, let-else and while let are shorthands.
  • Model states as enum variants to make illegal states unrepresentable.