11 / 35

Core Rust Concepts· 12 min read· Lesson 11 of 35

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”.

src/main.rs
#[derive(Debug)]
enum CupSize {
Small,
Medium,
Large,
}
fn main() {
let size = CupSize::Medium;
println!("You picked {size:?}");
}
Output
You picked Medium
  1. enum CupSize { ... } lists the three possible variants.
  2. You create a value with the enum name, ::, and the variant: CupSize::Medium.
  3. #[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.

src/main.rs
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");
}
Output
Large latte: 550 cents

Step by step:

  1. match size { ... } looks at the value of size.
  2. Each line is an arm: a pattern, then =>, then the code to run.
  3. match is 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:

Output
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.
src/main.rs
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));
}
}
Output
Cash, 1000 cents handed over
Card ending in 4242
Voucher FREECOFFEE

Let’s unpack it:

  1. Cash(u32) is a variant that holds one u32, like a tiny tuple.
  2. Card { last_four: String } holds a named field, like a tiny struct.
  3. In match, the pattern Payment::Cash(cents) pulls the data out into a new variable called cents. This is called destructuring.
  4. describe takes &Payment (a borrow), so we don’t move the payments out of the array.
  5. for payment in &payments loops over the array by reference. You saw for loops 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:

src/main.rs
#[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());
}
Output
Jo is making it

Matching more than enums

match also works on numbers, characters, and more. You can combine patterns with | (“or”) and use ranges with ..=:

src/main.rs
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));
}
Output
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:

src/main.rs
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");
}
}
Output
Change due: 225 cents
  1. if let Payment::Cash(given) = payment reads as: “if payment matches the Cash pattern, pull out the amount into given and run this block”.
  2. The optional else runs for every other variant.
  3. Unlike match, if let doesn’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

  1. Create an enum Milk with variants Whole, Oat, and Soy. Write fn milk_extra(milk: Milk) -> u32 using match: 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));
}
  1. Create an enum Order with variants Drink { name: String, size: u8 } and Food(String). Write a main that creates one of each and uses if let to 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-style Card { last_four: String }.
  • match runs the arm whose pattern fits, and can pull data out of variants.
  • match must be exhaustive: the compiler makes you handle every variant.
  • _ catches everything else. if let handles a single pattern without a full match.

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

Search lessons

Type to search all lessons.