Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Rust Pattern Matching: match Expressions, Guards, and if let Syntax

match is exhaustive and checked; guards are not. Destructuring, bindings with @, slice patterns, and the wildcard arm that quietly breaks when an enum grows.

~4 min readRust
#Rust#Control Flow#Pattern Matching
3D illustration of an exhaustive match tree splitting enum variants into guarded branching arms

Quick Summary

match in Rust is an expression that must be exhaustive: the compiler proves that every possible value is covered, and refuses to build otherwise. That single property replaces nullable checks, instanceof chains, and default-case conventions from other languages. Arms are evaluated top to bottom, the first match wins, and the compiler's exhaustiveness check tells you when a new enum variant leaves an arm missing.

Patterns do more than select variants. They destructure structs and tuples (Point { x, y }), bind parts of a value (Some(n @ 1..=9)), ignore with _, test with guards (n if n % 2 == 0), and reach into references (&Some(x)). if let is the one-arm shortcut for the common "do something only when it matches" case, and let ... else (Rust 1.65) is the shortcut for the opposite — extract and continue, or return early.

match is also checked for usefulness, not just completeness: an unreachable arm triggers unreachable_patterns, and a _ placed too early silently makes later arms dead code. Because nothing is evaluated lazily inside guards, moving a value in one arm and borrowing it in another is the most common way to make a match stop compiling.

Basic syntax and query signatures

rust
enum Shape { Circle(f64), Rect { w: f64, h: f64 }, Point } fn area(s: &Shape) -> f64 { match s { Shape::Circle(r) => std::f64::consts::PI * r * r, Shape::Rect { w, h } => w * h, Shape::Point => 0.0, } }
rust
let opt: Option<i32> = Some(3); match opt { Some(0) => println!("zero"), Some(n) if n < 0 => println!("negative {n}"), Some(n @ 1..=9) => println!("single digit {n}"), Some(n) => println!("large {n}"), None => println!("none"), } // Binding modes: match ergonomics let you skip the & when matching a reference let r: &Option<i32> = &opt; match r { Some(n) => println!("{n}"), // n is &i32 None => {} }

if let, while let, and let ... else cover the non-exhaustive cases:

rust
if let Some(v) = map.get("k") { println!("{v}"); } while let Some(job) = queue.pop() { process(job); } let Some(cfg) = load_config() else { eprintln!("no config"); return; }; use_config(cfg); // Chained let-else in a loop, with a labelled break 'outer: for row in rows { let Some(id) = row.get(0) else { continue 'outer }; let Ok(n) = id.parse::<u32>() else { continue }; println!("{n}"); }

Key comparison table

FormExhaustive requiredReturns a valueUse when
match x { ... }YesYesMultiple cases, all must be handled
if let P = xNoNoOne case, ignore the rest
if let ... elseNoNoTwo cases without nesting
let ... elseNoNo (diverges)Extract or bail out early
while let P = xNoNoLoop while the pattern matches
matches!(x, P)NoboolTest a pattern in a condition
x.is_some_and(f)NoboolTest the inner value of Option
PatternMatchesBinds
Some(x)The Some variantInner value
Point { x, y }A struct with both fieldsFields by name
Point { x, .. }A struct with at least xx only
(a, b)A two-element tupleBoth elements
[first, .., last]A slice with at least two itemsEnds only
n @ 1..=9A number in rangen
1 | 2 | 3Any of the alternativesNothing
_AnythingNothing
&Some(x)A reference to Somex by copy/ref per ergonomics

Practical edge cases and deep dives

1. Exhaustiveness breaks when someone else adds a variant

rust
enum State { Queued, Running, Done } fn label(s: State) -> &'static str { match s { State::Queued => "queued", State::Running => "running", State::Done => "done", } }

Adding State::Failed to the enum makes every non-wildcard match fail to compile — which is the feature, not the cost. Using _ => "other" here would compile today and silently mislabel the new state tomorrow. Reserve _ for genuinely open sets (integers, external data) rather than for enums you own.

2. Guards are not part of exhaustiveness

rust
let n: i32 = 5; match n { x if x > 0 => println!("positive"), // the compiler cannot prove this covers negatives: E0004 non-exhaustive patterns }

The compiler does not reason about guard conditions, so a guarded arm never contributes to coverage. The fix is an unguarded fallback:

rust
match n { x if x > 0 => println!("positive"), x if x < 0 => println!("negative"), _ => println!("zero"), }

3. Order matters, and _ early is a silent bug

rust
match code { 200 => "ok", _ => "other", // 404 => "not found", // unreachable_patterns warning: dead code }

Rust warns, not errors. Warnings are easy to ignore in a build log, and the wrong branch is only visible when a 404 shows as "other".

4. Moving out of a pattern versus borrowing

rust
let opt = Some(String::from("x")); match opt { Some(s) => println!("{s}"), // moves out of opt None => {} } // println!("{opt:?}"); // E0382: opt was moved // Non-consuming: match a reference, bind by reference match &opt { Some(s) => println!("{s}"), // s: &String None => {} } println!("{opt:?}"); // still valid

match opt.as_ref() or match &opt is the standard fix when the value must survive the match. The pattern-side alternative is ref s / ref mut s, though modern style prefers referencing the scrutinee.

5. Slice patterns for a cheap parser

rust
fn classify(cmd: &[&str]) -> &'static str { match cmd { [] => "empty", ["help"] => "help", ["get", key] => "get one", ["get", .., last] => "get range ending at a name", ["set", key, value] => "set", [first, ..] => { let _ = first; "unknown" } } } assert_eq!(classify(&["get", "a", "b"]), "get range ending at a name");

Slice patterns replace index checks and length arithmetic with a shape declaration, and the compiler still proves the arms are ordered correctly.

6. let ... else and diverging control flow

rust
fn parse_port(s: &str) -> Result<u16, String> { let Ok(port) = s.parse::<u16>() else { return Err(format!("invalid port: {s}")); }; if port == 0 { return Err("port 0 is reserved".into()); } Ok(port) }

The else block must diverge (return, break, continue, panic!). That restriction is what guarantees the binding after the statement is always valid.

7. Patterns in function parameters and let bindings

Patterns are not limited to match: parameters are irrefutable patterns, which is why destructuring a struct or tuple in a signature needs no body code.

rust
struct Point { x: i32, y: i32 } fn quadrant(Point { x, y }: Point) -> u8 { match (x >= 0, y >= 0) { (true, true) => 1, (false, true) => 2, (false, false) => 3, (true, false) => 4, } } // Destructure a tuple in a closure parameter let pairs = [(1, 'a'), (2, 'b')]; let letters: Vec<char> = pairs.iter().map(|&(_, c)| c).collect();

A destructuring parameter must be irrefutable, so fn f(Some(x): Option<i32>) fails with E0005 refutable pattern in function argument. Refutable patterns need match, if let, or let ... else.

8. Matching two values at once

Matching a tuple of scrutinees removes nested matches and is the clearest way to express a decision table.

rust
fn action(role: Role, state: State) -> Action { match (role, state) { (Role::Admin, _) => Action::Allow, (Role::Editor, State::Draft) => Action::Allow, (Role::Editor, State::Published) => Action::Review, (Role::Viewer, State::Published) => Action::Allow, (_, _) => Action::Deny, } }

(_, _) is required because the pair of enums has more combinations than the arms listed; the compiler counts them and reports E0004 if any remain uncovered. When the decision table is large, this shape is still better than a chain of if statements, because a new enum variant forces the table to be revisited.

9. Matching on Result without swallowing the error

rust
match read_file(path) { Ok(text) => handle(text), Err(e) if e.kind() == std::io::ErrorKind::NotFound => create_default(), Err(e) => return Err(e.into()), }

A _ => () arm here would discard the error, and that is the one place a wildcard is almost always wrong: filesystem and network errors need to reach the caller or the log.

Common mistakes and runtime errors

Error / symptomCauseFix
E0004 non-exhaustive patternsMissing variant, or coverage relies on guardsAdd the missing arm or an unguarded fallback
unreachable_patterns warningEarlier arm already covers itReorder or remove
E0382 use of moved value after a matchArm moved the scrutineeMatch &value or value.as_ref()
E0507 cannot move out of borrowed contentPattern moves from a referenceBind by reference
E0308 mismatched types in guardsComparing &str with StringCompare s == "x" or s.as_str()
Arm never runs_ placed before itMove _ last
let Some(x) = opt; compiles with a warninglet with a non-irrefutable patternUse let ... else or if let
E0005 refutable pattern in local bindingSame as above, newer compiler phrasinglet ... else
match on a float fails to compileFloats are not structural-matchCompare ranges with guards
Enum grows, match silently wrongWildcard used on an owned enumRemove the wildcard
Borrow error inside one armArm holds a borrow across a moveScope the borrow, split the arms

Try matching browser tools

All tools

Small utilities that fit Rust work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Rust guides

More in Rust

All Rust guides

The guides filed next to this one in Rust, in library order.