Model the choices that exist.
Represent alternatives without inventing invalid flag combinations.
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.
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");
}worker 7
- 1
Running carries a named worker field.
- 2
Failed owns its message.
- 3
The match handles every variant.
cargo run -p lesson_enums03 Mind the boundary
04 Your next build
Create a Delivery enum with Pickup and Courier(String), and return a description for each.
Reveal one possible solution +
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
What can an enum variant carry?
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.