Enums and Match
Part 1 · Rust. Model 'one of several choices' with enums, attach data to each choice, and handle every case safely with match and if let.
A drink at the Rusty Bean Café is small, medium or large. An order is waiting, being made, or ready. Payment is cash or card. This “exactly one of a few choices” shape shows up everywhere. Rust has a dedicated tool for it: the enum, together with its best friend, match.
What is an enum?
An enum (short for “enumeration”, which means “a list of options”) is a type whose value is exactly one of a fixed set of variants.
Picture the size buttons on the café’s till: Small, Medium, Large. You press exactly one. You can’t press “Medium-ish” or “Purple”.
#[derive(Debug)]enum CupSize { Small, Medium, Large,}
fn main() { let size = CupSize::Medium; println!("You picked {size:?}");}You picked Mediumenum CupSize { ... }lists the three possible variants.- You create a value with the enum name,
::, and the variant:CupSize::Medium. #[derive(Debug)]works on enums too, so we can print them with{:?}.
Note
Running this, you’ll also see warning: variants `Small` and `Large` are never constructed. The compiler noticed we only ever used Medium. Warnings are hints, not errors, and the program still runs. Small examples in this lesson often skip some variants, so you can safely ignore these “never constructed” warnings here.
Compare this with storing the size as a String. Nothing would stop someone from typing "meduim". With an enum, a typo is a compile error, not a bug a customer finds.
match: handling each variant
To do something different for each variant, use match. It compares a value against patterns and runs the code of the first one that fits.
enum CupSize { Small, Medium, Large,}
fn extra_cents(size: CupSize) -> u32 { match size { CupSize::Small => 0, CupSize::Medium => 50, CupSize::Large => 100, }}
fn main() { let latte_cents = 450 + extra_cents(CupSize::Large); println!("Large latte: {latte_cents} cents");}Large latte: 550 centsStep by step:
match size { ... }looks at the value ofsize.- Each line is an arm: a pattern, then
=>, then the code to run. matchis an expression, so it produces a value. Here it returns the extra cost, which becomes the function’s return value.
Match must be exhaustive
Here’s the safety superpower. A match must cover every possible variant. Imagine the café adds an ExtraLarge size and forgets to update the price function:
error[E0004]: non-exhaustive patterns: `CupSize::ExtraLarge` not covered --> src/main.rs:9:11 | 9 | match size { | ^^^^ pattern `CupSize::ExtraLarge` not covered |note: `CupSize` defined here --> src/main.rs:1:6 | 1 | enum CupSize { | ^^^^^^^... 5 | ExtraLarge, | ---------- not covered = note: the matched value is of type `CupSize`help: ensure that all possible cases are being handled by adding a match arm with a wildcard pattern or an explicit pattern as shown |12 ~ CupSize::Large => 100,13 ~ CupSize::ExtraLarge => todo!(), |Rust tells you exactly which case you forgot. In a bigger program, this catches every place you need to update when a new option is added.
Tip
When you add a variant to an enum, compile straight away. The list of “not covered” errors is a free to-do list of everything that needs updating.
The catch-all _
Sometimes you only care about a few cases. The pattern _ means “anything else”:
fn is_big(size: CupSize) -> bool { match size { CupSize::Large => true, _ => false, }}Warning
Use _ with care. If you later add ExtraLarge, the _ quietly catches it and you get no compiler reminder. Listing every variant is often the safer choice.
Enums with data
This is where Rust enums get much more powerful than in many other languages. Each variant can carry its own data, and the data can differ from variant to variant.
Think about payment at the café:
- Cash: we need to know how much the customer handed over.
- Card: we need the last four digits for the receipt.
- Voucher: we need the voucher code.
enum Payment { Cash(u32), Card { last_four: String }, Voucher(String),}
fn describe(payment: &Payment) -> String { match payment { Payment::Cash(cents) => format!("Cash, {cents} cents handed over"), Payment::Card { last_four } => format!("Card ending in {last_four}"), Payment::Voucher(code) => format!("Voucher {code}"), }}
fn main() { let payments = [ Payment::Cash(1000), Payment::Card { last_four: String::from("4242") }, Payment::Voucher(String::from("FREECOFFEE")), ];
for payment in &payments { println!("{}", describe(payment)); }}Cash, 1000 cents handed overCard ending in 4242Voucher FREECOFFEELet’s unpack it:
Cash(u32)is a variant that holds oneu32, like a tiny tuple.Card { last_four: String }holds a named field, like a tiny struct.- In
match, the patternPayment::Cash(cents)pulls the data out into a new variable calledcents. This is called destructuring. describetakes&Payment(a borrow), so we don’t move the payments out of the array.for payment in &paymentsloops over the array by reference. You sawforloops in Control Flow.
One type, Payment, can now represent three very different situations, and match forces you to handle each one correctly.
Methods on enums
Enums can have impl blocks, just like structs:
#[derive(Debug)]enum OrderStatus { Waiting, Brewing { barista: String }, Ready,}
impl OrderStatus { fn message(&self) -> String { match self { OrderStatus::Waiting => String::from("In the queue"), OrderStatus::Brewing { barista } => format!("{barista} is making it"), OrderStatus::Ready => String::from("Ready at the counter!"), } }}
fn main() { let status = OrderStatus::Brewing { barista: String::from("Jo") }; println!("{}", status.message());}Jo is making itMatching more than enums
match also works on numbers, characters, and more. You can combine patterns with | (“or”) and use ranges with ..=:
fn stamp_message(stamps: u32) -> &'static str { match stamps { 0 => "Welcome! Here's your first loyalty card.", 1..=8 => "Keep going!", 9 => "One more for a free coffee!", _ => "Free coffee time!", }}
fn main() { println!("{}", stamp_message(9));}One more for a free coffee!The return type &'static str means “a piece of text that lives for the whole program”, which is what text in quotes is. You don’t need to understand the 'static part yet.
if let: when you only care about one case
Writing a full match just to handle one variant can feel heavy. if let is a shorter form:
enum Payment { Cash(u32), Card { last_four: String },}
fn main() { let payment = Payment::Cash(1000); let total_cents: u32 = 775;
if let Payment::Cash(given) = payment { println!("Change due: {} cents", given - total_cents); } else { println!("No change needed"); }}Change due: 225 centsif let Payment::Cash(given) = paymentreads as: “ifpaymentmatches theCashpattern, pull out the amount intogivenand run this block”.- The optional
elseruns for every other variant. - Unlike
match,if letdoesn’t force you to cover every case. That’s handy but less safe, so pick the tool that fits.
The compiler warns that the Card variant is never constructed, because this tiny example only ever makes Cash. That’s fine (see the note at the top of this page).
Try it yourself
- Create an enum
Milkwith variantsWhole,Oat, andSoy. Writefn milk_extra(milk: Milk) -> u32usingmatch: whole is free, oat costs 60 cents, soy costs 50 cents.
Show solution
enum Milk { Whole, Oat, Soy,}
fn milk_extra(milk: Milk) -> u32 { match milk { Milk::Whole => 0, Milk::Oat => 60, Milk::Soy => 50, }}
fn main() { println!("Oat milk adds {} cents", milk_extra(Milk::Oat));}- Create an enum
Orderwith variantsDrink { name: String, size: u8 }andFood(String). Write amainthat creates one of each and usesif letto print only the drink’s name.
Show solution
enum Order { Drink { name: String, size: u8 }, Food(String),}
fn main() { let orders = [ Order::Drink { name: String::from("Mocha"), size: 2 }, Order::Food(String::from("Bagel")), ];
for order in &orders { if let Order::Drink { name, .. } = order { println!("Drink: {name}"); } }}The .. in the pattern means “ignore the remaining fields”. The compiler may warn that size and Food’s data are never read, which is fine here.
Recap
- An enum is a type whose value is exactly one of several variants.
- Variants can carry data, either tuple-style
Cash(u32)or struct-styleCard { last_four: String }. matchruns the arm whose pattern fits, and can pull data out of variants.matchmust be exhaustive: the compiler makes you handle every variant._catches everything else.if lethandles a single pattern without a fullmatch.
What’s next
Rust’s two most important enums are built in: Option and Result. Meet them in Option and Result.
0 of 35 lessons complete