The Match Control Flow

The Match Control Flow in Rust: A postal sorting frame is a wall of labelled pigeonholes. The sorter picks up a letter, reads the address, and works across the…

The Analogy: The Sorting Frame

A postal sorting frame is a wall of labelled pigeonholes. The sorter picks up a letter, reads the address, and works across the frame dropping it into the first hole whose label covers it. Not the best-fitting hole -- the first one. That single rule is what makes hand sorting fast enough to be worth doing at all.

Because the order decides the outcome, the frame is laid out from most specific to least. "SW1A 1AA" comes before "SW1A", which comes before "SW", which comes before "London". Put a broad hole too early and every specific hole behind it will sit empty for weeks without anyone noticing, because the letters still get delivered -- just to the wrong depot.

The frame always ends with one hole labelled "further examination". Not out of laziness, but because a letter must never end up on the floor. Every item that comes off the belt has to be in a hole when the shift ends, and the supervisor's sign-off is precisely a check that the frame has somewhere to put any address that could conceivably arrive.

Rust's match is that frame with the supervisor built into the compiler. Arms are tried top to bottom and the first one that matches wins. A _ arm is the "further examination" hole. And the sign-off is not advisory: an uncovered case is error[E0004]: non-exhaustive patterns, and the program does not build. That is what separates match from a switch statement in most other languages. It is not only a way of choosing a branch -- it is a proof that you considered every case, and because it is an expression, its value can be the answer itself.


Syntax or Core Structure

Three matches, doing three different jobs. The first returns a value from a payload, the second routes a string, the third sorts a number into a band.

#[derive(Debug)]
enum Band {
    Letter,
    LargeLetter,
    SmallParcel { kg: u32 },
    Medium { kg: u32, tracked: bool },
}

fn price_pence(b: &Band) -> u32 {
    // match is an expression, so this is the whole function body.
    match b {
        Band::Letter => 85,
        Band::LargeLetter => 135,
        // Patterns bind the payload for the arm to use.
        Band::SmallParcel { kg } => 340 + kg * 40,
        Band::Medium { kg, tracked } => 610 + kg * 40 + if *tracked { 90 } else { 0 },
    }
}

fn depot(postcode: &str) -> &'static str {
    // Arms are tried top to bottom; the first one that matches wins.
    match postcode {
        "SW1A 1AA" => "Westminster (special)",
        p if p.starts_with("SW1A") => "Westminster",
        p if p.starts_with("SW") => "South West London",
        p if p.starts_with("EC") => "City of London",
        _ => "further examination",
    }
}

fn band_of(grams: u32) -> &'static str {
    match grams {
        0 => "invalid",
        1..=100 => "Letter",
        101..=750 => "Large Letter",
        751..=2000 => "Small Parcel",
        _ => "Medium Parcel",
    }
}

fn main() {
    let bands = [
        Band::Letter,
        Band::LargeLetter,
        Band::SmallParcel { kg: 2 },
        Band::Medium { kg: 5, tracked: true },
    ];
    for b in &bands {
        println!("{:>4}  {:?}", price_pence(b), b);
    }

    println!();
    for p in ["SW1A 1AA", "SW1A 2AB", "SW19 4TQ", "EC1A 1BB", "M1 1AE"] {
        println!("{:<9} -> {}", p, depot(p));
    }

    println!();
    for g in [0, 60, 400, 1500, 9000] {
        println!("{:>5} g -> {}", g, band_of(g));
    }
}

Output:

  85  Letter
 135  LargeLetter
 420  SmallParcel { kg: 2 }
 900  Medium { kg: 5, tracked: true }

SW1A 1AA  -> Westminster (special)
SW1A 2AB  -> Westminster
SW19 4TQ  -> South West London
EC1A 1BB  -> City of London
M1 1AE    -> further examination

    0 g -> invalid
   60 g -> Letter
  400 g -> Large Letter
 1500 g -> Small Parcel
 9000 g -> Medium Parcel

depot is the sorting frame verbatim. "SW19 4TQ" fails the exact-literal arm, fails starts_with("SW1A") because the fourth character is a nine, and lands in starts_with("SW"). Reverse those two arms and "SW1A 2AB" would be sorted to South West London and the Westminster arm would never fire again -- the program would still run, still print, and still be wrong.

Now remove an arm and watch the supervisor refuse to sign:

enum Band {
    Letter,
    LargeLetter,
    SmallParcel,
}

fn price(b: &Band) -> u32 {
    match b {
        Band::Letter => 85,
        Band::LargeLetter => 135,
    }
}

Output:

error[E0004]: non-exhaustive patterns: `&Band::SmallParcel` not covered
 --> src/main.rs:8:11
  |
8 |     match b {
  |           ^ pattern `&Band::SmallParcel` not covered
  |
note: `Band` defined here
 --> src/main.rs:1:6
  |
1 | enum Band {
  |      ^^^^
2 |     Letter,
3 |     LargeLetter,
4 |     SmallParcel,
  |     ----------- not covered
  = note: the matched value is of type `&Band`
help: ensure the expression is exhaustive by adding a match arm with the missing pattern

The error names the exact pattern that is missing and points at the variant that produced it. That is the property worth building a codebase around: add a variant to Band next year and every match that needs updating reports itself, by file and line, before the program runs.


Technical Depth: Patterns, Order and Proof

The pattern catalogue

PatternWhat it matchesWorth knowing
5, 'c', "text", trueone literal valuea string literal matches a &str scrutinee directly
1..=9an inclusive rangeintegers and char only, and the range must be closed
xanything, and binds itshadows any outer x for the length of the arm
_anything, binds nothingnever raises an unused-variable warning
Some(x)a tuple-like variantbinds the payload by position
Point { x, y }a struct or struct variantthe shorthand binds each field to its own name
Point { x, .. }the same, ignoring the rest.. may appear once per pattern
(a, b, c)a tuplethe arity must match exactly
[a, b]a slice or array of length twothe length is part of the pattern
[first, .., last]two or more elements.. covers zero or more in the middle
rest @ ..the skipped middle, bound as a sliceonly legal inside a slice pattern
n @ 1..=9a range, and binds the matched valuethe @ binding

Alternatives are written with a vertical bar, and they compose with everything else:

fn kind(c: char) -> &'static str {
    match c {
        'a' | 'e' | 'i' | 'o' | 'u' => "vowel",
        'a'..='z' | 'A'..='Z' => "consonant",
        '0'..='9' => "digit",
        ' ' | '\t' | '\n' => "space",
        _ => "other",
    }
}

The second arm is only reached by letters the first arm declined, which is the sorting frame again -- and it is why "consonant" is correct there and would be wrong anywhere above the vowel arm.

match is an expression, so every arm agrees on a type

fn main() {
    let pair = (true, false);
    // No catch-all needed: four arms cover every (bool, bool) there is.
    let s = match pair {
        (true, true) => "both",
        (true, false) => "first only",
        (false, true) => "second only",
        (false, false) => "neither",
    };
    println!("{s}");

    // Integers need a catch-all, because listing four billion arms is not an option.
    let n: u32 = 7;
    let t = match n {
        0 => "zero",
        1..=9 => "single digit",
        _ => "larger",
    };
    println!("{t}");
}

Output:

first only
single digit

Exhaustiveness is computed from the type, not from a rule about needing a _. A bool needs two arms. A (bool, bool) needs four, or two with a _ in one position. An Option<bool> needs three. A u32 needs a catch-all or a range covering the whole type. And because every arm feeds the same let, all of them must produce the same type -- mixing a &str arm with an i32 arm is error[E0308], "match arms have incompatible types", reported against whichever arm first disagreed with the one above it.

Guards are checked after the pattern, and do not count as coverage

fn sign(v: Option<i32>) -> &'static str {
    match v {
        Some(n) if n > 0 => "positive",
        Some(n) if n < 0 => "negative",
        Some(_) => "zero",
        None => "absent",
    }
}

That compiles. Delete the Some(_) arm and it does not, even though a human can see that > 0, < 0 and None leave only zero uncovered. The exhaustiveness checker deliberately does not reason about the contents of a guard -- it treats every guarded arm as one that might not match -- so a guard can never be the thing that completes a match. Two more facts about guards are easy to get wrong: a guard can read variables from outside the match, which patterns cannot, and a guard attaches to the whole or-pattern, so 1 | 2 if flag means (1 or 2) if flag and not 1, or 2-when-flag.

Order, and the warning that tells you it is wrong

fn main() {
    let n = 5;
    let s = match n {
        _ => "anything",
        5 => "five",
    };
    println!("{s}");
}

Output:

warning: unreachable pattern
 --> src/main.rs:5:9
  |
5 |         5 => "five",
  |         ^ no value can reach this
  |
  = note: `#[warn(unreachable_patterns)]` on by default

It is a warning, not an error, which is exactly why it is worth promoting. The program compiles, runs, prints anything, and the misplaced arm scrolls past in a build log. Recent compiler versions also add a note pointing at the earlier arm that shadows it; either way, a #![deny(unreachable_patterns)] at the crate root turns a build-log line into a build failure.

Slice patterns describe structure

fn describe(xs: &[i32]) -> String {
    match xs {
        [] => String::from("empty"),
        [only] => format!("one element: {only}"),
        [first, last] => format!("two: {first} and {last}"),
        [first, .., last] => format!("{} elements, {first}..{last}", xs.len()),
    }
}

fn main() {
    let cases: [&[i32]; 4] = [&[], &[9], &[1, 2], &[1, 2, 3, 4]];
    for xs in cases {
        println!("{:?} -> {}", xs, describe(xs));
    }
}

Output:

[] -> empty
[9] -> one element: 9
[1, 2] -> two: 1 and 2
[1, 2, 3, 4] -> 4 elements, 1..4

That match is exhaustive with no _ at all: lengths zero, one, two, and two-or-more between them cover every slice. The compiler knows it, which means the arms can index nothing and check nothing -- there is no xs.len() >= 2 anywhere, and no way to read past the end.


Real World Example: Routing an HTTP Request

Routing is a two-dimensional decision -- the method and the path -- and a match on a tuple takes both dimensions in one pass. The path is split into segments so that slice patterns can describe its shape instead of the code doing string surgery.

enum Method {
    Get,
    Post,
    Delete,
}

#[derive(Debug)]
enum Route {
    Home,
    Health,
    ListUsers,
    CreateUser,
    ShowUser(u32),
    DeleteUser(u32),
    UserPosts { user: u32, page: u32 },
    MethodNotAllowed,
    NotFound,
}

fn method_name(m: &Method) -> &'static str {
    match m {
        Method::Get => "GET",
        Method::Post => "POST",
        Method::Delete => "DELETE",
    }
}

fn route(method: &Method, path: &str) -> Route {
    let segs: Vec<&str> = path.split('/').filter(|s| !s.is_empty()).collect();

    // Most specific first. Every route in the service is one line.
    match (method, segs.as_slice()) {
        (Method::Get, []) => Route::Home,
        (Method::Get, ["health"]) => Route::Health,
        (Method::Get, ["users"]) => Route::ListUsers,
        (Method::Post, ["users"]) => Route::CreateUser,
        (Method::Get, ["users", id]) => id
            .parse()
            .ok()
            .map(Route::ShowUser)
            .unwrap_or(Route::NotFound),
        (Method::Delete, ["users", id]) => id
            .parse()
            .ok()
            .map(Route::DeleteUser)
            .unwrap_or(Route::NotFound),
        (Method::Get, ["users", id, "posts"]) => id
            .parse()
            .ok()
            .map(|user| Route::UserPosts { user, page: 1 })
            .unwrap_or(Route::NotFound),
        (Method::Get, ["users", id, "posts", page]) => id
            .parse()
            .ok()
            .zip(page.parse().ok())
            .map(|(user, page)| Route::UserPosts { user, page })
            .unwrap_or(Route::NotFound),
        // Paths we recognise, arriving under a method we do not serve.
        (_, ["users", ..]) => Route::MethodNotAllowed,
        (_, ["health"]) => Route::MethodNotAllowed,
        _ => Route::NotFound,
    }
}
fn main() {
    let requests = [
        (Method::Get, "/"),
        (Method::Get, "/health"),
        (Method::Get, "/users"),
        (Method::Post, "/users"),
        (Method::Get, "/users/42"),
        (Method::Delete, "/users/42"),
        (Method::Get, "/users/42/posts"),
        (Method::Get, "/users/42/posts/3"),
        (Method::Get, "/users/abc"),
        (Method::Delete, "/health"),
        (Method::Post, "/users/42"),
        (Method::Get, "/admin/secrets"),
    ];

    for (m, p) in &requests {
        println!("{:<6} {:<18} -> {:?}", method_name(m), p, route(m, p));
    }
}

Output:

GET    /                  -> Home
GET    /health            -> Health
GET    /users             -> ListUsers
POST   /users             -> CreateUser
GET    /users/42          -> ShowUser(42)
DELETE /users/42          -> DeleteUser(42)
GET    /users/42/posts    -> UserPosts { user: 42, page: 1 }
GET    /users/42/posts/3  -> UserPosts { user: 42, page: 3 }
GET    /users/abc         -> NotFound
DELETE /health            -> MethodNotAllowed
POST   /users/42          -> MethodNotAllowed
GET    /admin/secrets     -> NotFound

The routing table is the match, and reading it top to bottom is reading the precedence rules. There is no framework, no registry, no string comparison chain -- just a scrutinee of (&Method, &[&str]) and eleven patterns. Adding a route means adding a line in the right place, and the compiler will not let the function forget to return something.

Ordering does the work that an if chain would need explicit negations for. POST /users/42 walks past the four exact arms, past (Method::Get, ["users", id]) because the method is wrong, and lands in (_, ["users", ..]) -- so the "wrong method" arm sees only requests the specific arms declined, and needs no conditions of its own. Move that arm to the top of the match and every user route in the service returns 405, with no error and no warning beyond the unreachable-pattern lint.

The slice patterns are what keep the path handling honest. ["users", id, "posts", page] says "exactly four segments, the first and third fixed, the second and fourth captured" in one line that cannot go out of bounds and cannot get an index wrong. Compare it to segs.len() == 4 && segs[0] == "users" && segs[2] == "posts" followed by reading segs[1] and segs[3], and count the opportunities for an off-by-one.

Three honest limits. split('/') and collect allocate a Vec for every request, which a production router avoids with a trie or a compiled table -- this design trades throughput for a routing table you can read. The parse failures collapse into NotFound where a 400 would be more truthful, because Option has thrown away the reason; that is the seam where Result belongs. And (_, ["health"]) sitting below (Method::Get, ["health"]) is duplication that grows linearly with the number of paths -- a larger service resolves the path first and checks the method second, so that 405 is decided in one place instead of once per route.


Common Mistakes

  1. Putting the broad arm before the specific one. match n { 1..=100 => "letter", 1..=10 => "tiny", _ => "big" } never returns "tiny", because the first arm already accepted 1 through 10. The compiler does warn here -- unreachable_patterns -- but only when it can prove the later arm is fully covered. Add a guard to the broad arm and the proof disappears, the warning goes with it, and the dead branch ships. Order arms most specific first and read the match top-down as a priority list.
  1. Reaching for _ when you mean "the rest of today's variants". A catch-all is a promise to handle every variant that will ever exist, including the one a colleague adds next month. Band::Letter => 85, _ => 0 compiles happily after someone adds Band::Pallet, and quietly prices it at zero. Where the set of variants is yours to control, list them and let E0004 be the reminder; save _ for genuinely open sets like u32 or for #[non_exhaustive] types you do not own.
  1. Expecting a guard to count towards exhaustiveness. match n { x if x < 0 => "neg", x if x >= 0 => "non-neg" } is rejected with error[E0004]: non-exhaustive patterns, and rustc names the entire remaining range of the type as uncovered. The exhaustiveness checker reasons about patterns only; it never evaluates a guard expression, so as far as it is concerned both arms might decline. Make the final case unconditional: x if x < 0 => "neg", _ => "non-neg".
  1. Misreading how far a guard reaches over an or-pattern. 1 | 2 if flag => ... parses as (1 | 2) if flag, not 1 | (2 if flag). The guard is attached to the arm, so it gates both alternatives, and a value of 1 with flag false falls through to a later arm. If you want the condition on only one alternative, write two arms.
  1. Arms that return different types. Every arm must produce the same type, because the match is one expression with one value. match ok { true => 1, false => "no" } fails with error[E0308], "match arms have incompatible types", pointing at the second arm and naming the type the first one established. Fix the arm, or convert both to a common type such as String.
  1. Writing return in every arm and losing the expression. match x { 1 => return "one", _ => return "other" } works but throws away the reason to use match at all: it can no longer be assigned, passed as an argument, or made the tail expression of a function. Drop the returns, let the match evaluate to the value, and put it where the value is needed.
  1. Moving out of the scrutinee by accident. match msg { Message::Text(s) => s.len(), _ => 0 } moves the String out of msg when msg is owned, so msg is unusable afterwards and a later use is error[E0382]: borrow of moved value. Match on a reference instead -- match &msg -- and match ergonomics bind s as &String without any ref keyword.
  1. Binding a name where you meant to compare with a variable. let wanted = 3; match n { wanted => "hit", _ => "miss" } always says "hit": wanted in pattern position is a new binding that shadows the outer one and matches anything. The unreachable_patterns warning on the _ arm is the only clue. Use a guard -- x if x == wanted -- or make the value a const, which pattern position treats as a literal.
  1. Leaning on .. in struct patterns and then adding a field. Config { host, .. } => ... keeps compiling when port is added, which is convenient until the field is one you needed to react to. .. is right for fields you are deliberately ignoring and wrong as a shortcut for "I did not want to type them"; naming the fields you care about and leaving .. only over genuinely irrelevant ones keeps the compiler as your reviewer.

Best Practices

  • Read a match as a priority list and order it most specific first. The first pattern that fits wins, so the layout of the arms is the specification. If two arms could both match a value, the one you want should be higher.
  • Prefer exhaustive variant lists over _ for your own enums. The compile error you get when a variant is added is the cheapest possible reminder to handle it. Reserve _ for open-ended scrutinees and for the tail of a long list where the remaining cases genuinely share one behaviour.
  • Match on a reference when you only need to look. match &value (or match value.as_slice(), match self) leaves ownership where it is, and match ergonomics still give you plain-looking bindings. Reach for a move only when the arm actually needs to take the data.
  • Use a tuple scrutinee when a decision has two dimensions. match (method, path_segments) puts both axes in one exhaustive table instead of a method match nested inside a path match, and the compiler checks the combinations for you.
  • Let slice and struct patterns describe shape instead of testing it. [first, .., last], [only], Point { x: 0, y } state a structural claim that cannot index out of bounds. Length checks followed by indexing express the same idea with more places to be wrong.
  • Keep guards small and side-effect free. A guard runs during matching, possibly for several candidate arms, so it should be a cheap predicate over the bindings. Anything that mutates, allocates heavily, or can panic belongs in the arm body.
  • Bind with @ when you need both the test and the value. n @ 1..=100 => println!("in band: {n}") avoids re-deriving what the pattern already proved, and keeps the range written exactly once.
  • Collapse arms with or-patterns rather than repeating a body. 'a' | 'e' | 'i' | 'o' | 'u' => "vowel" is one arm and one behaviour; five arms with identical bodies is five places for them to drift apart.

Practice Exercises

  1. Rock, paper, scissors in nine arms. Define enum Move { Rock, Paper, Scissors } and enum Outcome { Win, Lose, Draw }, then write fn play(mine: &Move, theirs: &Move) -> Outcome as a single match on the tuple (mine, theirs) with no catch-all and no guards -- all nine combinations spelled out. Print a 3x3 grid of results using a &'static str helper for each enum so the columns line up, then delete one arm and read the E0004 message to see exactly which pair the compiler says is missing.
  1. A command parser built from slice patterns. Write fn parse(line: &str) -> Command that splits on whitespace and matches the resulting &[&str]. Handle [] as Command::Empty, ["quit"] and ["exit"] as one arm, ["set", key, value], ["get", key], ["echo", rest @ ..] (joining rest back together with spaces), and anything else as Command::Unknown. Feed it at least seven lines including "set port 8080", "echo hello there world" and "set port", and check that the last one lands in Unknown rather than silently dropping an argument.
  1. An exhaustiveness experiment. Take the Band enum from the Syntax section, add a fifth variant Band::Pallet { kg: u32 }, and compile without touching price_pence. Record the full error text. Now replace the explicit arms with Band::Letter => 85 plus _ => 0, compile again, and note that it succeeds while pricing pallets at nothing. Write two or three sentences in a comment explaining which version you would rather inherit and why.
  1. From if chain to match. Rewrite this function as one match using inclusive ranges, with no guards and no _ arm reachable for scores 0 through 100:
    fn grade(score: u32) -> &'static str {
        if score >= 90 { "A" }
        else if score >= 80 { "B" }
        else if score >= 70 { "C" }
        else if score >= 60 { "D" }
        else { "F" }
    }

Note which boundary values you had to write twice in the match that the if chain left implicit, then test 0, 59, 60, 69, 89, 90 and 100 against both versions to confirm they agree.