Module 4 · Control flow & pattern matching
4.2Exhaustive match & destructuring
How Rust's match replaces switch, why the compiler refuses a match that misses a case, and how patterns take tuples, structs and enums apart.
On this page
Concept map
| Concept | TypeScript | C# | Rust |
|---|---|---|---|
| Branch on a value | switch statement | switch expression | match expression |
| A case is missing | Compiles, unless a never check or the declared return type catches it | Warning CS8509, then an exception at runtime | Compile error E0004 |
| Several values, one branch | Stacked case labels (fall-through) | or patterns | | patterns, and never any fall-through |
| Extra condition on a branch | An if inside the case | when clause | if guard |
| Take a value apart | Destructuring: const { x, y } = point | Deconstruction and property patterns: { X: 0 } | Patterns in let, match and parameters: Point { x: 0, y } |
| Does it match? (a bool) | A comparison or .includes() | is pattern | matches! macro |
TypeScript’s switch compares a value against cases, falls through when you forget a break, and checks for missing cases only when you force it to.C#‘s switch expression matches patterns but only warns when a case is missing. Rust’s match is a switch expression with patterns, and the compiler proves it handles every possible value before the program can run. The same patterns also work in let and function parameters, to take tuples, structs and enums apart.
match must cover every case
Here’s a traffic light in both languages. TypeScript uses a string union, Rust an enum.C# and Rust both use an enum. Each function says how long a light stays on.
type Light = "red" | "yellow" | "green";
function seconds(light: Light): number {
switch (light) {
case "red":
return 30;
case "yellow":
return 3;
case "green":
return 25;
default: {
const unhandled: never = light; // fails to compile if a case is missing
return unhandled;
}
}
}
console.log(`yellow lasts ${seconds("yellow")}s`);Console.WriteLine($"yellow lasts {Seconds(Light.Yellow)}s");
static int Seconds(Light light) => light switch
{
Light.Red => 30,
Light.Yellow => 3,
Light.Green => 25,
_ => throw new ArgumentOutOfRangeException(nameof(light)),
};
enum Light { Red, Yellow, Green }enum Light {
Red,
Yellow,
Green,
}
fn seconds(light: Light) -> u32 {
match light {
Light::Red => 30,
Light::Yellow => 3,
Light::Green => 25,
}
}
fn main() {
println!("yellow lasts {}s", seconds(Light::Yellow));
}Output
yellow lasts 3s
The shape is close to C#: each armEach arm is pattern => value, separated by commas, and the whole match is an expression. Rust needs no default_ arm at all:
-
TypeScript checks the cases only when something forces it: a
nevercheck like this one, or a declared return type that every path must produce. Aswitchthat only runs code, with no return value, isn’t checked.C# warns (CS8524) without the_arm, because a C# enum is just anint:(Light)42is a validLight, so the compiler can’t trust the three names. Leave the arm out and(Light)42throwsSwitchExpressionExceptionat run time. - A Rust enum value is always one of its variants. The three arms cover everything, and the compiler knows it.
Now forget a case. Rust refuses to compile, and names the variant you missed:
enum Light {
Red,
Yellow,
Green,
}
fn seconds(light: Light) -> u32 {
match light {
Light::Red => 30,
Light::Yellow => 3,
}
}
fn main() {
println!("{}", seconds(Light::Green));
}Rust doesn't compile this: error E0004
error[E0004]: non-exhaustive patterns: `Light::Green` not covered
--> main.rs:8:11
|
8 | match light {
| ^^^^^ pattern `Light::Green` not covered
|
note: `Light` defined here
--> main.rs:1:6
|
1 | enum Light {
| ^^^^^
...
4 | Green,
| ----- not covered
= note: the matched value is of type `Light`
help: ensure that all possible cases are being handled by adding a match arm with a wildcard pattern or an explicit pattern as shown
|
10~ Light::Yellow => 3,
11~ Light::Green => todo!(),
|Caught at compile timeAdd a variant, find every match
When you add Blinking to Light, every match on a Light stops compiling until it handles the new variant. The compiler gives you a to-do list. In C#, the _ arm keeps compiling and throws at runtime.In TypeScript, only the switches with a never check or a declared return type catch it.
Alternatives, ranges and the catch-all _
Patterns aren’t limited to enum names. An arm can list alternatives with |, match a range of numbers with ..=, and end with _ for “anything else”:
function describe(code: number): string {
if (code === 200 || code === 204) return "success";
if (code === 404) return "not found";
if (code >= 400 && code <= 499) return `client error ${code}`;
if (code >= 500 && code <= 599) return `server error ${code}`;
return `unexpected ${code}`;
}
for (const code of [204, 404, 418, 503, 302]) {
console.log(describe(code));
}foreach (var code in new[] { 204, 404, 418, 503, 302 })
{
Console.WriteLine(Describe(code));
}
static string Describe(int code) => code switch
{
200 or 204 => "success",
404 => "not found",
>= 400 and <= 499 => $"client error {code}",
>= 500 and <= 599 => $"server error {code}",
_ => $"unexpected {code}",
};fn describe(code: u16) -> String {
match code {
200 | 204 => String::from("success"),
404 => String::from("not found"),
400..=499 => format!("client error {code}"),
500..=599 => format!("server error {code}"),
_ => format!("unexpected {code}"),
}
}
fn main() {
for code in [204, 404, 418, 503, 302] {
println!("{}", describe(code));
}
}Output
success not found client error 418 server error 503 unexpected 302
- Arms are tried top to bottom, and the first match wins.
404comes before400..=499so it gets its own message. If you swap them, the compiler warns that the404arm is unreachable. - There’s no fall-through. Each arm runs alone, so there’s no
breakto forget.200 | 204is how you share one arm. _is required here, because au16has 65,536 possible values and the other arms cover only some of them.
Here’s the path every code takes through describe. Each arm is one question, and the first “yes” gives the answer:
Is
code200or204?YesNo"success"Is it
404?YesNo"not found"Asked before400..=499, so 404 never reaches the next arm.Is it in
400..=499?YesNo"client error {code}"Is it in
500..=599?YesNo"server error {code}"Otherwise:
_matches anything left:"unexpected {code}"
Destructuring structs, tuples and enums
A pattern can describe the shape of a value: fixed parts to compare, and names to bind. This is the real power of match. Here a point is located on a grid, with a guard (if ...) for the diagonal:
type Point = { x: number; y: number };
function locate(point: Point): string {
const { x, y } = point;
if (x === 0 && y === 0) return "origin";
if (x === 0) return `on the y axis at ${y}`;
if (y === 0) return `on the x axis at ${x}`;
if (x === y) return `on the diagonal at ${x}`;
return `at (${x}, ${y})`;
}
console.log(locate({ x: 0, y: 0 }));
console.log(locate({ x: 0, y: 5 }));
console.log(locate({ x: 2, y: 2 }));
console.log(locate({ x: 1, y: 4 }));Console.WriteLine(Locate(new Point(0, 0)));
Console.WriteLine(Locate(new Point(0, 5)));
Console.WriteLine(Locate(new Point(2, 2)));
Console.WriteLine(Locate(new Point(1, 4)));
static string Locate(Point point) => point switch
{
{ X: 0, Y: 0 } => "origin",
{ X: 0, Y: var y } => $"on the y axis at {y}",
{ X: var x, Y: 0 } => $"on the x axis at {x}",
{ X: var x, Y: var y } when x == y => $"on the diagonal at {x}",
{ X: var x, Y: var y } => $"at ({x}, {y})",
};
readonly record struct Point(int X, int Y);struct Point {
x: i32,
y: i32,
}
fn locate(point: Point) -> String {
match point {
Point { x: 0, y: 0 } => String::from("origin"),
Point { x: 0, y } => format!("on the y axis at {y}"),
Point { x, y: 0 } => format!("on the x axis at {x}"),
Point { x, y } if x == y => format!("on the diagonal at {x}"),
Point { x, y } => format!("at ({x}, {y})"),
}
}
fn main() {
println!("{}", locate(Point { x: 0, y: 0 }));
println!("{}", locate(Point { x: 0, y: 5 }));
println!("{}", locate(Point { x: 2, y: 2 }));
println!("{}", locate(Point { x: 1, y: 4 }));
}Output
origin on the y axis at 5 on the diagonal at 2 at (1, 4)
Read Point { x: 0, y } as “a Point whose x is 0; call its y field y”. A literal compares, a name binds. The C# property pattern { X: 0, Y: var y } is the same idea with more punctuation.In TypeScript you destructure with const { x, y } = point and then test the parts with if; a Rust pattern does both in one step.
Tuples, .. and @
Tuples destructure the same way, which makes match on two values at once easy. Two more pieces of syntax help:
..skips the fields you don’t care about:Point { x, .. },(first, ..).name @ patternchecks a pattern and keeps the value under a name. Use it when you need both the test and the value, like a range check on a tuple field.
let order = ("Ada", 3);
match order {
(_, 0) => println!("empty order"),
(name, quantity @ 1..=9) => println!("{name} wants {quantity}"),
(name, quantity) => println!("{name} wants a bulk order of {quantity}"),
}The same patterns work outside match, wherever Rust binds a name. A let or a function parameter can take a tuple or struct apart, as long as the pattern can’t fail:
let (name, quantity) = ("Ada", 3);
let point = (4, -2);
let (x, y) = point;
println!("{name} {quantity} {x} {y}");Enums that carry data
Rust enum variants can hold values, and match is how you get them back out. Here’s a small taste; Enums with data covers them properly.
enum Command {
Quit,
Move { x: i32, y: i32 },
Say(String),
}
let command = Command::Move { x: 3, y: 0 };
match command {
Command::Quit => println!("bye"),
Command::Move { x, y: 0 } => println!("move right by {x}"),
Command::Move { x, y } => println!("move to ({x}, {y})"),
Command::Say(text) => println!("{text}"),
}{ kind: "move"; x: number }), this is the same idea, with the kind check and the field access done in one pattern.Move(var x, 0). A Rust enum keeps all the cases in one closed type, so match knows every one of them.matches! for yes-or-no questions
Sometimes you only need a bool: does this value fit the pattern? matches!(value, pattern) answers that without writing a full match with true and false arms. It’s Rust’s version of C#‘s is pattern.Think of it as .includes() or a chain of === checks, but for any pattern.
const word = "ownership";
let vowels = 0;
for (const c of word) {
if ("aeiou".includes(c)) {
vowels++;
}
}
console.log(`${vowels} vowels`);var word = "ownership";
var vowels = 0;
foreach (var c in word)
{
if (c is 'a' or 'e' or 'i' or 'o' or 'u')
{
vowels++;
}
}
Console.WriteLine($"{vowels} vowels");let word = "ownership";
let mut vowels = 0;
for c in word.chars() {
if matches!(c, 'a' | 'e' | 'i' | 'o' | 'u') {
vowels += 1;
}
}
println!("{vowels} vowels");Output
3 vowels
matches! takes any pattern, guards included: matches!(code, 200..=299), matches!(light, Light::Red | Light::Yellow), matches!(point, Point { x, y } if x == y). The ! marks a macro call; Module 13 explains macros.
Which one should I use?
| What | When | Why | How |
|---|---|---|---|
match | You branch on the shape or value of one thing: an enum, a tuple, a number with ranges. | The compiler checks that every case is handled, and patterns bind the parts you need. | match value { pattern => result, ... } |
if / else if chain | The conditions test unrelated things (if retries > 3 ... else if user.is_admin ...). | Patterns can’t express “this variable is above that one” across unrelated values. | Ordinary if cond { } else if other { } |
matches! | You need a bool: in an if, a filter or a return. | Shorter than a match with true and false arms. | matches!(c, 'a' | 'e') |
Guard (if on an arm) | One arm needs a condition a pattern can’t say, like x == y. | Keeps the logic in the match. | Point { x, y } if x == y => ... |
@ binding | You test part of a value with a pattern and also need that part. | Avoids repeating the value or matching twice. | quantity @ 1..=9 => ... |
_ catch-all | Values with too many cases to list: numbers, strings, chars. | Required for exhaustiveness there. | Last arm: _ => ... |
Every variant listed (no _) | Matching your own enum. | A new variant then breaks the build at every match that must handle it. | Write one arm per variant, or group them with |. |
Rule of thumb: branch on one value with match, ask yes-or-no with matches!, and keep if for conditions that aren’t about one value’s shape. On your own enums, list every variant instead of writing _, so the compiler can tell you when a new one needs handling.
Under the hood
How the compiler checks exhaustiveness
The compiler treats each pattern as a set of values it covers. Working down the arms, it asks two questions:
- Does this arm match anything the arms above it don’t? If not, it warns that the arm is unreachable.
- After the last arm, is any value left over? If so, the program doesn’t compile, and the error shows an example of a missing value.
This works for nested shapes too: a tuple of two enums is checked as every combination, and a struct as every combination of its fields. Integer ranges are tracked exactly, so the compiler can say which numbers you missed:
let code: u16 = 404;
let kind = match code {
200..=299 => "success",
400..=499 => "client error",
};
println!("{kind}");Rust doesn't compile this: error E0004
error[E0004]: non-exhaustive patterns: `0_u16..=199_u16`, `300_u16..=399_u16` and `500_u16..=u16::MAX` not covered
--> main.rs:2:18
|
2 | let kind = match code {
| ^^^^ patterns `0_u16..=199_u16`, `300_u16..=399_u16` and `500_u16..=u16::MAX` not covered
|
= note: the matched value is of type `u16`
help: ensure that all possible cases are being handled by adding a match arm with a wildcard pattern, a match arm with multiple or-patterns as shown, or multiple match arms
|
4 ~ 400..=499 => "client error",
5 ~ 0_u16..=199_u16 | 300_u16..=399_u16 | 500_u16..=u16::MAX => todo!(),
|All of this happens at compile time. At runtime, a match is as cheap as a switch: the compiler emits comparisons or a jump table, and there’s no hidden default branch that throws.
Common pitfalls
Common pitfallGuards don't count toward exhaustiveness
To a human, n if n < 0 and n if n >= 0 cover every number. The compiler doesn’t evaluate guards when it checks coverage, so it still sees a gap:
let n = 5;
match n {
n if n < 0 => println!("negative"),
n if n >= 0 => println!("zero or more"),
}Rust doesn't compile this: error E0004
error[E0004]: non-exhaustive patterns: `i32::MIN..=i32::MAX` not covered
--> main.rs:2:7
|
2 | match n {
| ^ pattern `i32::MIN..=i32::MAX` not covered
|
= note: the matched value is of type `i32`
= note: match arms with guards don't count towards exhaustivity
help: ensure that all possible cases are being handled by adding a match arm with a wildcard pattern or an explicit pattern as shown
|
4 ~ n if n >= 0 => println!("zero or more"),
5 ~ i32::MIN..=i32::MAX => todo!(),
|Make the last arm unconditional: _ => println!("zero or more").
Common pitfallA name in a pattern binds, it doesn't compare
In TypeScript, case expected: compares against whatever expected holds.In C#, case expected: compares against a constant. In a Rust pattern, a lowercase name like expected creates a new variable that matches anything, so every later arm is unreachable. The compiler warns (“unreachable pattern”), but the code still builds. Compare against a variable with a guard:
let expected = 3;
let guess = 3;
match guess {
g if g == expected => println!("correct"),
_ => println!("try again"),
}Constants (const MAX: u32 = 10;) and enum variants like Light::Red do compare, because they aren’t new names.
Common pitfallMatching by value moves the fields out
Binding a String field in a pattern moves it, so you can’t use the whole value afterwards:
enum Command {
Quit,
Say(String),
}
let command = Command::Say(String::from("hi"));
match command {
Command::Say(text) => println!("{text}"),
Command::Quit => println!("bye"),
}
let again = command;Rust doesn't compile this: error E0382
error[E0382]: use of partially moved value: `command`
--> main.rs:11:13
|
8 | Command::Say(text) => println!("{text}"),
| ---- value partially moved here
...
11 | let again = command;
| ^^^^^^^ value used here after partial move
|
= note: partial move occurs because value has type `String`, which does not implement the `Copy` trait
help: borrow this binding in the pattern to avoid moving the value
|
8 | Command::Say(ref text) => println!("{text}"),
| +++Match on &command instead. Then text is a &String, and command stays whole.
Try it yourself
Exercise: port this to Rust
Port this rock-paper-scissors scorer to Rust. Use an enum for the hands and one match on the tuple (me, them).
type Hand = "rock" | "paper" | "scissors";
const beats: Record<Hand, Hand> = { rock: "scissors", paper: "rock", scissors: "paper" };
function outcome(me: Hand, them: Hand): string {
if (me === them) return "draw";
return beats[me] === them ? "win" : "lose";
}
console.log(outcome("rock", "scissors"));
console.log(outcome("paper", "scissors"));
console.log(outcome("rock", "rock"));Console.WriteLine(Outcome(Hand.Rock, Hand.Scissors));
Console.WriteLine(Outcome(Hand.Paper, Hand.Scissors));
Console.WriteLine(Outcome(Hand.Rock, Hand.Rock));
static string Outcome(Hand me, Hand them) => (me, them) switch
{
_ when me == them => "draw",
(Hand.Rock, Hand.Scissors) or (Hand.Paper, Hand.Rock) or (Hand.Scissors, Hand.Paper) => "win",
_ => "lose",
};
enum Hand { Rock, Paper, Scissors }Expected output
win lose draw
Show a hint
Derive PartialEq on Hand so you can compare two hands with ==. Then match on the tuple (me, them): a guard arm for a draw, one arm that lists the three winning pairs with |, and _ for the rest.
Show a solution
#[derive(Clone, Copy, PartialEq)]
enum Hand {
Rock,
Paper,
Scissors,
}
fn outcome(me: Hand, them: Hand) -> &'static str {
match (me, them) {
_ if me == them => "draw",
(Hand::Rock, Hand::Scissors)
| (Hand::Paper, Hand::Rock)
| (Hand::Scissors, Hand::Paper) => "win",
_ => "lose",
}
}
fn main() {
println!("{}", outcome(Hand::Rock, Hand::Scissors));
println!("{}", outcome(Hand::Paper, Hand::Scissors));
println!("{}", outcome(Hand::Rock, Hand::Rock));
}Matching on a tuple checks both hands in one pattern. The draw arm uses a guard because a pattern can't say both sides are equal. The winning pairs share one arm through |, and _ covers the remaining losing pairs.
Saved in this browser only.