Skip to lesson content
navan✳THE BUILD LABRUST
0/53 complete
BUILD LAB / RUST/ MODEL THE DOMAIN
BUILD NOTE 16 / 53

Model the choices that exist.

Represent alternatives without inventing invalid flag combinations.

BY NAVAN SAMI◷ 7 MIN READFOUNDATIONSRUST 2024

01 Understand the contract

An enum describes one of several variants, and each variant can carry a different data shape. This is useful for states such as queued, running with a worker ID, or failed with a message. A pair of booleans could express contradictory combinations; an enum can make those states unrepresentable. Pattern matching inspects the variant and binds its data. Derive traits only when their behavior fits the data, and prefer domain types to magic strings for closed sets of choices.

02 Make it concrete

This is a complete standard-library example. Use Rust stable with the 2024 edition. Run it locally using the Rust workbench.

lessons/enums/src/main.rs
enum Job {
    Queued,
    Running { worker: u32 },
    Failed(String),
}
fn describe(job: Job) -> String {
    match job {
        Job::Queued => "queued".into(),
        Job::Running { worker } => format!("worker {worker}"),
        Job::Failed(reason) => format!("failed: {reason}"),
    }
}
fn main() {
    println!("{}", describe(Job::Running { worker: 7 }));
    assert_eq!(describe(Job::Queued), "queued");
    assert_eq!(describe(Job::Failed("offline".into())), "failed: offline");
}
↳ EXPECTED OUTPUT
worker 7
  1. 1

    Running carries a named worker field.

  2. 2

    Failed owns its message.

  3. 3

    The match handles every variant.

From the extracted rust-workbench folder
cargo run -p lesson_enums

03 Mind the boundary

04 Your next build

A SMALL MISSION

Create a Delivery enum with Pickup and Courier(String), and return a description for each.

Reveal one possible solution +
solutions/enums/src/main.rs
enum Delivery {
    Pickup,
    Courier(String),
}
fn label(d: Delivery) -> String {
    match d {
        Delivery::Pickup => "collect".into(),
        Delivery::Courier(city) => format!("send to {city}"),
    }
}
fn main() {
    assert_eq!(label(Delivery::Pickup), "collect");
    assert_eq!(label(Delivery::Courier("Durban".into())), "send to Durban");
}

05 Check your reasoning

QUICK SIGNAL CHECK

What can an enum variant carry?

ONE MORE CONTRACT YOU CAN EXPLAIN.

Understand it.
Then make it yours.

Run the example, try your own input, and explain the boundary. Log the lesson when the idea makes sense.

Built with curiosity. By Navan Sami. ↗Rust · Make the contract clear. Then build.