An enum is a value that is one of several shapes, and match makes you handle every shape. This part covers enums with data, match and its patterns, Option instead of null, if let, let else and while let.
A struct holds several values at once. An enum holds one value that can be one of several kinds, and each kind can carry its own data. match is how you look inside one, and the compiler checks that you’ve handled every kind.
This part covers enums and their variants, match and its patterns, and Option, Rust’s answer to null. Then it covers the shorter forms: if let, let else, while let and matches!. It builds on structs and methods from Part 10. Every program here was run on Rust 1.95, and its output is pasted from the run.
Try this first
A traffic light is red, yellow or green. next says which colour comes after the current one. Decide what this prints before you scroll down:
#[derive(Debug)]
enum Light {
Red,
Yellow,
Green,
}
fn next(light: Light) -> Light {
match light {
Light::Red => Light::Green,
Light::Green => Light::Yellow,
}
}
fn main() {
println!("{:?}", next(Light::Red));
}
It doesn’t compile:
error[E0004]: non-exhaustive patterns: `Light::Yellow` not covered
...
9 | match light {
| ^^^^^ pattern `Light::Yellow` not covered
...
4 | Yellow,
| ------ not covered
We never asked about yellow, and the program never even makes a yellow light reach next. The compiler still refuses. A match must have an answer for every possible value, and a Light might be yellow. The error names the missing case, Light::Yellow, and points at where it’s defined.
This check is called exhaustiveness, and it’s the main reason Rust programmers like enums. When you add a new kind of value later, the compiler finds every match that doesn’t handle it yet.
An enum is one of several variants
enum Light { Red, Yellow, Green } defines a new type, Light. A Light value is exactly one of the three variants: Light::Red, Light::Yellow or Light::Green. You name a variant with the enum’s name, two colons, and the variant’s name.
#[derive(Debug)]
enum Light {
Red,
Yellow,
Green,
}
fn main() {
let lights = [Light::Red, Light::Green, Light::Yellow];
for light in &lights {
println!("{light:?}");
}
}
It prints:
Red
Green
Yellow
#[derive(Debug)] works the same as it did for structs in Part 10: it lets {:?} print the value. For an enum, that prints the variant’s name.
In languages like C or Java, an enum like this is a list of named numbers. A Rust enum can do that too, but it can also carry data, and that’s where it gets useful.
Variants that carry data
Here is a shape. A square has a side length. A rectangle has a width and a height. A dot has no size at all. The enum lists the three, and a method works out the area of each:
#[derive(Debug)]
enum Shape {
Square(u32),
Rect { w: u32, h: u32 },
Dot,
}
impl Shape {
fn area(&self) -> u32 {
match self {
Shape::Square(s) => s * s,
Shape::Rect { w, h } => w * h,
Shape::Dot => 0,
}
}
}
fn main() {
let shapes = [Shape::Square(5), Shape::Rect { w: 3, h: 4 }, Shape::Dot];
for s in &shapes {
println!("{s:?} has area {}", s.area());
}
}
It prints:
Square(5) has area 25
Rect { w: 3, h: 4 } has area 12
Dot has area 0
The three variants show the three ways a variant can look:
Square(u32)carries values by position, like a tuple struct from Part 10. You make one withShape::Square(5).Rect { w: u32, h: u32 }carries named fields, like an ordinary struct. You make one withShape::Rect { w: 3, h: 4 }.Dotcarries nothing, like the colours ofLight.
All three are the same type, Shape, so they fit in one array. A struct couldn’t do this. With structs you’d need three types, and an array holds only one type.
An enum can have methods in an impl block, exactly like a struct. The match inside area is where the work happens. Let’s go through it slowly.
How match works
A match takes a value and a list of arms. Each arm is a pattern, then =>, then an expression. Rust tries the patterns from the top down. The first one that fits wins: its expression runs, and its value becomes the value of the whole match. The other arms are skipped.
A pattern can do two jobs at once. It checks the shape of the value, and it binds names to the parts inside. Shape::Rect { w, h } checks “is this a Rect?”, and if it is, it makes two new variables, w and h, holding the rectangle’s width and height. Those variables exist only inside that arm.
The animation steps through Shape::Rect { w: 3, h: 4 }.area():
A match tries its arms in order. The first pattern that fits binds the value’s fields to new names, runs its arm, and ends the match.
Here are those steps in words, in case the animation doesn’t play for you:
matchtakes the valueShape::Rect { w: 3, h: 4 }and starts at the first arm.- The first arm’s pattern is
Shape::Square(s). The value isn’t aSquare, so this arm doesn’t match. Rust moves to the next arm. - The second arm’s pattern is
Shape::Rect { w, h }. The value is aRect, so the pattern fits. - The pattern binds the fields: inside this arm,
wis 3 andhis 4. - The arm’s expression,
w * h, gives 12. That’s the value of the wholematch, and so the return value ofarea. The third arm is never checked.
One detail in area: it matches on self, which is a &Shape, a reference. When you match on a reference, the names a pattern binds are references too, so s, w and h are &u32. Multiplying two &u32 works and gives a u32, so we didn’t need the * from Part 7. The reference also means match only looks at the shape. It doesn’t move anything out of it.
match is an expression
Like if in Part 3, match gives back a value. Every arm must give the same type. When an arm needs more than one line, give it a block, { ... }, and the block’s last expression is the arm’s value:
#[derive(Debug)]
enum Light {
Red,
Yellow,
Green,
}
fn main() {
for light in [Light::Red, Light::Yellow, Light::Green] {
let seconds = match light {
Light::Red => 30,
Light::Yellow => {
println!(" (yellow is short)");
3
}
Light::Green => 25,
};
println!("{light:?} lasts {seconds} s");
}
}
It prints:
Red lasts 30 s
(yellow is short)
Yellow lasts 3 s
Green lasts 25 s
Every case, or it doesn’t compile
Go back to Try this first. Its match had arms for red and green. The compiler knows every variant of Light, so it could see that yellow had no arm, and it named it in the error: pattern `Light::Yellow` not covered. When several are missing, it names them, up to three, and then says how many more.
There are two ways to fix a missing case. One is to add an arm for it. The other is the wildcard pattern, _, which matches anything and binds nothing. It’s useful for values with too many cases to list, like numbers. On your own enums, it hides something. Here’s a light with a new variant, Off, for a broken signal:
#[derive(Debug)]
enum Light {
Red,
Yellow,
Green,
Off,
}
fn advice(light: &Light) -> &'static str {
match light {
Light::Red | Light::Yellow => "stop",
_ => "go",
}
}
fn main() {
for light in [Light::Red, Light::Yellow, Light::Green, Light::Off] {
println!("{light:?}: {}", advice(&light));
}
}
It prints:
Red: stop
Yellow: stop
Green: go
Off: go
advice was written when there were three lights. The _ arm meant “green”. When someone added Off, the _ quietly caught it too, and now the program says “go” at a broken traffic light. Nothing warned anyone.
If the last arm had been Light::Green => "go", adding Off would have made this an E0004 error, and the compiler would have pointed straight at advice. So on your own enums, prefer to list the variants. Keep _ for when you really do mean “everything else, now and later”.
The arm Light::Red | Light::Yellow shows another pattern: | means “or”. The arm runs if either pattern fits.
More patterns
Patterns can do more than name a variant. Here are the ones you’ll use most.
Literals and ranges. A pattern can be a number, a character or a string literal. For numbers and characters, it can also be a range. 1..=15 means 1 to 15, both included. ..=0 means “0 or less” and 26.. means “26 or more”:
fn feel(celsius: i32) -> &'static str {
match celsius {
..=0 => "freezing",
1..=15 => "cold",
16..=25 => "mild",
26.. => "hot",
}
}
fn main() {
for t in [-5, 0, 12, 20, 31] {
println!("{t:>3}: {}", feel(t));
}
}
It prints:
-5: freezing
0: freezing
12: cold
20: mild
31: hot
There’s no _ here, and none is needed. The compiler checked that the four ranges together cover every i32. Change 26.. to 26..=40 and it reports E0004, with pattern `41_i32..=i32::MAX` not covered.
Tuples. You can match several values at once by putting them in a tuple. Here is FizzBuzz, written as one match on two remainders:
fn fizzbuzz(n: i32) -> String {
match (n % 3, n % 5) {
(0, 0) => String::from("FizzBuzz"),
(0, _) => String::from("Fizz"),
(_, 0) => String::from("Buzz"),
_ => n.to_string(),
}
}
fn main() {
for n in 9..=15 {
println!("{n}: {}", fizzbuzz(n));
}
}
It prints:
9: Fizz
10: Buzz
11: 11
12: Fizz
13: 13
14: 14
15: FizzBuzz
(0, _) means “the first is 0, and the second can be anything”. The order of the arms matters: 15 fits (0, 0) and (0, _), and the first arm that fits wins.
Guards. An arm can add a condition after the pattern with if. The arm runs only if the pattern fits and the condition is true:
enum Shape {
Square(u32),
Rect { w: u32, h: u32 },
Dot,
}
fn describe(s: &Shape) -> String {
match s {
Shape::Rect { w, h } if w == h => format!("a {w}x{h} rect, really a square"),
Shape::Rect { w, h } => format!("a {w}x{h} rect"),
Shape::Square(side) => format!("a square of side {side}"),
Shape::Dot => String::from("a dot"),
}
}
fn main() {
let shapes = [
Shape::Rect { w: 2, h: 2 },
Shape::Rect { w: 3, h: 4 },
Shape::Square(5),
Shape::Dot,
];
for s in &shapes {
println!("{}", describe(s));
}
}
It prints:
a 2x2 rect, really a square
a 3x4 rect
a square of side 5
a dot
The compiler doesn’t look inside guards when it checks exhaustiveness. If we deleted the second Rect arm, it would report E0004 for Rect, even though the guard arm catches some rectangles. That’s what we want: a guard can be false, so a guarded arm never counts as covering its pattern.
Option: a value that might not be there
Many languages have null: a value that means “nothing here”. Most variables can hold it, so almost any use of a variable might crash. Rust has no null. Instead, the standard library has an enum:
enum Option<T> {
None,
Some(T),
}
The T means “any type”. Part 15 explains these generic types; for now, read Option<u32> as “maybe a u32“. A value of that type is either None, nothing, or Some(n), a u32 called n wrapped up inside. Option, Some and None are always in scope, so you write Some(5), not Option::Some(5).
You’ve met Option before. In Part 2, checked_add gave None on overflow. In Part 5, .chars().nth(1) gave Some('é'). Here’s a function that returns one:
fn find(names: &[&str], target: &str) -> Option<usize> {
for (i, name) in names.iter().enumerate() {
if *name == target {
return Some(i);
}
}
None
}
fn main() {
let names = ["Ana", "Ben", "Cai"];
for target in ["Ben", "Zoe"] {
match find(&names, target) {
Some(i) => println!("{target} is at index {i}"),
None => println!("{target} is not in the list"),
}
}
}
It prints:
Ben is at index 1
Zoe is not in the list
The return type says, out loud, that find might not find anything. The caller can’t forget that, because an Option<usize> isn’t a usize. You can’t use it as a number until you’ve taken the number out:
fn main() {
let price: Option<i32> = Some(5);
let total = price + 1;
println!("{total}");
}
It prints:
error[E0369]: cannot add `{integer}` to `Option<i32>`
...
3 | let total = price + 1;
| ----- ^ - {integer}
| |
| Option<i32>
Read it as: “you asked me to add a number to an Option<i32>, and there’s no rule for that”. {integer} is how the compiler writes “some integer type I haven’t decided yet”. What should None + 1 be? There’s no good answer, so Rust makes you decide. That’s the whole point: in a language with null, this line would compile and fail later, at run time, on the one input where the value was missing.
if let: when you care about one case
A full match is a lot of typing when you only care about one variant. if let takes one pattern. If the value fits, the block runs with the bindings. If not, the else runs, if there is one:
fn main() {
let words = ["apple", "", "kiwi"];
for w in words {
if let Some(c) = w.chars().next() {
println!("{w:?} starts with {c}");
} else {
println!("{w:?} is empty");
}
}
}
It prints:
"apple" starts with a
"" is empty
"kiwi" starts with k
if let doesn’t check exhaustiveness. That’s its job: it’s for “do something in this one case”. When you need a different answer for every variant, use match.
let else: get the value or leave
Often the case you want is the normal one, and the other cases mean “give up here”. let else says that directly. The pattern must fit, or the else block runs, and that block must leave: return, break, continue or a panic. After the statement, the bound names can be used as plain values:
fn initials(full_name: &str) -> String {
let mut parts = full_name.split_whitespace();
let Some(first) = parts.next() else {
return String::from("?");
};
let Some(last) = parts.last() else {
return first.chars().take(1).collect();
};
let f = first.chars().next().unwrap_or('?');
let l = last.chars().next().unwrap_or('?');
format!("{f}{l}")
}
fn main() {
for name in ["Ada Lovelace", "Grace Brewster Hopper", "Cher", ""] {
println!("{name:?} -> {}", initials(name));
}
}
It prints:
"Ada Lovelace" -> AL
"Grace Brewster Hopper" -> GH
"Cher" -> C
"" -> ?
Without let else, each step would push the rest of the function one level deeper inside an if let. With it, the happy path reads straight down the page, and each early exit sits right next to the thing it checked. .chars().take(1).collect() turns the first character into a String; Part 17 covers iterators properly.
while let: loop while it fits
while let repeats as long as the pattern fits. Vec::pop takes the last item off a vector and returns it as Some(item), or None when the vector is empty. That makes them a natural pair:
fn main() {
let mut stack = vec![1, 2, 3];
while let Some(top) = stack.pop() {
println!("popped {top}, {} left", stack.len());
}
println!("empty: {:?}", stack);
}
It prints:
popped 3, 2 left
popped 2, 1 left
popped 1, 0 left
empty: []
matches!: a yes or no
Sometimes you only want to know whether a value fits a pattern. matches! gives back a bool, and it takes | and guards like a match arm does:
#[derive(Debug)]
enum Light {
Red,
Yellow,
Green,
}
fn main() {
let lights = [Light::Red, Light::Green, Light::Yellow, Light::Red];
let must_stop = lights
.iter()
.filter(|l| matches!(l, Light::Red | Light::Yellow))
.count();
println!("{must_stop} of {} lights say stop", lights.len());
let n = Some(42);
println!("big? {}", matches!(n, Some(x) if x > 10));
}
It prints:
3 of 4 lights say stop
big? true
The |l| ... is a closure, a small function written in place. Part 16 covers closures. Here, read .filter(|l| test) as “keep the items where the test is true”. Clippy also likes matches!. If you write a match whose arms give only true and false, it suggests matches! instead.
A few Option methods
Option has many methods that save you writing a match. Two cover a lot of everyday code:
unwrap_or(default)gives the value inside aSome, ordefaultforNone.map(f)changes the value inside aSomeand leavesNonealone.
fn main() {
let scores = [70, 85, 92];
let none: [i32; 0] = [];
let best = scores.iter().max();
let nothing = none.iter().max();
println!("{best:?} {nothing:?}");
println!("best or 0: {}", best.copied().unwrap_or(0));
println!("empty or 0: {}", nothing.copied().unwrap_or(0));
let doubled = best.map(|b| b * 2);
let still_none = nothing.map(|b| b * 2);
println!("{doubled:?} {still_none:?}");
}
It prints:
Some(92) None
best or 0: 92
empty or 0: 0
Some(184) None
iter().max() returns an Option, because an empty list has no largest item. It’s an Option<&i32>, a reference into the array, and .copied() turns it into an Option<i32>. map takes a closure again; Part 16 explains it.
Each of these is a short match underneath. unwrap_or(0) is match best { Some(v) => v, None => 0 }. When a method’s name says what you mean, use it. When it doesn’t, a match is always fine.
There are also unwrap and expect, which take the value out and panic on None. The second worked example shows that. And in Part 12, the ? operator gives a shorter way to say “if this is None, return None from my function”.
Worked example: a door that knows its rules
A door can be open, closed or locked. Some actions make sense only in some states: you can’t lock an open door, and you can’t open a locked one. That’s a state machine, and a match on a tuple of (state, action) writes one down in a few lines.
The program reads a list of action words. An unknown word is skipped with let else.
#[derive(Debug, Clone, Copy)]
enum Door {
Open,
Closed,
Locked,
}
#[derive(Debug, Clone, Copy)]
enum Action {
Open,
Close,
Lock,
Unlock,
}
fn parse(word: &str) -> Option<Action> {
match word {
"open" => Some(Action::Open),
"close" => Some(Action::Close),
"lock" => Some(Action::Lock),
"unlock" => Some(Action::Unlock),
_ => None,
}
}
fn step(door: Door, action: Action) -> Door {
match (door, action) {
(Door::Closed, Action::Open) => Door::Open,
(Door::Open, Action::Close) => Door::Closed,
(Door::Closed, Action::Lock) => Door::Locked,
(Door::Locked, Action::Unlock) => Door::Closed,
(same, _) => {
println!(" can't {action:?} a door that is {same:?}");
same
}
}
}
fn main() {
let mut door = Door::Closed;
for word in ["lock", "open", "unlock", "open", "kick", "lock", "close"] {
let Some(action) = parse(word) else {
println!(" unknown action {word:?}");
continue;
};
door = step(door, action);
println!("{word:>6} -> {door:?}");
}
}
It prints:
lock -> Locked
can't Open a door that is Locked
open -> Locked
unlock -> Closed
open -> Open
unknown action "kick"
can't Lock a door that is Open
lock -> Open
close -> Closed
Things to notice:
DoorandActionboth have a variant calledOpen. That’s fine, because you always write the enum’s name:Door::OpenandAction::Opendon’t clash.- The last arm,
(same, _), matches any pair. It also binds the door state tosame, so the arm can print it and hand it back unchanged. Here the catch-all is the honest choice: “every other combination does nothing” is the rule we want, now and for any action added later. parsereturnsOption<Action>. Its_ => Noneis fine too. A string has endless possible values, so there’s nothing to list.- In
main,let elsewithcontinueskips the bad word and keeps the loop going. Everything after it usesactionas a plainAction. #[derive(Clone, Copy)]letssteptake both enums by value and still useactionin the message. Part 6 explainedCopy. A unit-only enum is a single small number, so copying it is cheap.
Worked example: the unwrap that panicked
Here’s a function that finds the first word of a line, and a caller that’s sure there’s always one:
fn first_word(line: &str) -> Option<&str> {
line.split_whitespace().next()
}
fn main() {
let lines = ["hello world", " "];
for line in lines {
let word = first_word(line).unwrap();
println!("first word: {word}");
}
}
It prints:
first word: hello
...
panicked at src/main.rs:8:37:
called `Option::unwrap()` on a `None` value
Read the panic from the top. panicked at src/main.rs:8:37 is the place: line 8, column 37, which is the .unwrap() call. The message says what happened: unwrap was called on a None. The second line, " ", is only spaces, so it has no first word, and first_word correctly said None. The function was right. The caller was wrong to assume.
unwrap means “I’m sure this is Some, and if I’m wrong, crash”. expect("message") is the same, with your message in the panic. Both are fine in a quick test, or where None would truly be a bug. Here, a blank line is normal input, so we should handle it. Pick the fix by what a blank line should mean:
fn first_word(line: &str) -> Option<&str> {
line.split_whitespace().next()
}
fn main() {
let lines = ["hello world", " ", "rust"];
for line in lines {
match first_word(line) {
Some(word) => println!("match: {word}"),
None => println!("match: (blank line)"),
}
}
for line in lines {
let word = first_word(line).unwrap_or("-");
println!("unwrap_or: {word}");
}
for line in lines {
let Some(word) = first_word(line) else {
continue;
};
println!("let else: {word}");
}
}
It prints:
match: hello
match: (blank line)
match: rust
unwrap_or: hello
unwrap_or: -
unwrap_or: rust
let else: hello
let else: rust
matchwhen a blank line needs its own behaviour.unwrap_orwhen there’s a sensible stand-in value.let elsewhen a blank line should just be skipped.
Tips and traps
- A
_arm on your own enum. It compiles today, and it silently swallows the variant someone adds next year, asOffdid above. List the variants, so that adding one gives E0004 at everymatchthat needs a decision. - A pattern that’s never reached. If an earlier arm already covers everything a later one would, the compiler warns
unreachable pattern. Usually a_or a plain binding likensits above a more specific arm. Put specific arms first. - A binding where you meant a constant. In a pattern, a lowercase name is a new variable, and it matches anything.
match x { limit => ... }doesn’t comparexwith a variable calledlimit; it makes a newlimit. Compare in a guard instead:n if n == limit. unwrapin real code. A panic withcalled `Option::unwrap()` on a `None` valuemeans aNoneyou didn’t expect. Usematch,if let,let elseorunwrap_or, orexpectwith a message that says why it can’t beNone.- A
matchwith one useful arm.match opt { Some(x) => ..., _ => {} }gets a clippy warning,single_match. Writeif let Some(x) = opt { ... }instead. - Forgetting that
let elsemust leave. Theelseblock can’t fall through. If it doesn’treturn,break,continueor panic, you get E0308,`else` clause of `let...else` does not diverge. The code after it needs the bound names to exist, so falling through isn’t allowed.
An enum lists every shape a value can take, and
matchmakes you answer for each one.
Exercises
Exercise 1. Add a variant Circle(u32) to Shape, holding a radius. Before you change area, build it and read the error. Then make area handle circles, using 3 as a rough value of pi so that it stays a u32.
Exercise 2. Write fn sign(n: Option<i32>) -> &'static str that gives "nothing" for None, "zero" for Some(0), "negative" for a number below zero, and "positive" otherwise. Use one match, with a guard.
Exercise 3. You have let readings = vec![Some(12), None, Some(3), Some(40), None];. Use while let and pop to print each reading from the last to the first, printing missing for a None. Then, on a fresh copy of the list, use matches! to count the readings that are above 10.
Answers
1. Adding the variant alone gives E0004 in area:
enum Shape {
Square(u32),
Rect { w: u32, h: u32 },
Dot,
Circle(u32),
}
impl Shape {
fn area(&self) -> u32 {
match self {
Shape::Square(s) => s * s,
Shape::Rect { w, h } => w * h,
Shape::Dot => 0,
}
}
}
fn main() {
println!("{}", Shape::Circle(2).area());
}
It prints:
error[E0004]: non-exhaustive patterns: `&Shape::Circle(_)` not covered
The pattern has a & in front because area matches on &self, a reference. The fix is one arm:
enum Shape {
Square(u32),
Rect { w: u32, h: u32 },
Dot,
Circle(u32),
}
impl Shape {
fn area(&self) -> u32 {
match self {
Shape::Square(s) => s * s,
Shape::Rect { w, h } => w * h,
Shape::Dot => 0,
Shape::Circle(r) => 3 * r * r,
}
}
}
fn main() {
let shapes = [
Shape::Square(5),
Shape::Rect { w: 3, h: 4 },
Shape::Dot,
Shape::Circle(2),
];
for s in &shapes {
println!("area {}", s.area());
}
}
It prints:
area 25
area 12
area 0
area 12
2. Some(0) comes before the guard arm, and the guard arm before the plain Some(_), because the first arm that fits wins:
fn sign(n: Option<i32>) -> &'static str {
match n {
None => "nothing",
Some(0) => "zero",
Some(x) if x < 0 => "negative",
Some(_) => "positive",
}
}
fn main() {
for n in [None, Some(0), Some(-4), Some(7)] {
println!("{n:?}: {}", sign(n));
}
}
It prints:
None: nothing
Some(0): zero
Some(-4): negative
Some(7): positive
3. pop returns Option<Option<i32>> here: the outer Option says whether there was an item, and the inner one is the item. while let Some(reading) takes off the outer layer, and a match handles the inner one.
fn main() {
let readings = vec![Some(12), None, Some(3), Some(40), None];
let mut stack = readings.clone();
while let Some(reading) = stack.pop() {
match reading {
Some(v) => println!("{v}"),
None => println!("missing"),
}
}
let above_10 = readings
.iter()
.filter(|r| matches!(r, Some(v) if *v > 10))
.count();
println!("{above_10} readings above 10");
}
It prints:
missing
40
3
missing
12
2 readings above 10
In the matches!, r is a reference to an item, so v is a &i32, and *v reads the number, as in Part 7.
What’s next
Option says “maybe there’s a value”. In Part 12, we’ll meet its sibling Result, which says “a value, or the reason there isn’t one”, and the ? operator that passes failures up to the caller.