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.

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
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,
}
}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:
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
| Form | Exhaustive required | Returns a value | Use when |
|---|---|---|---|
match x { ... } | Yes | Yes | Multiple cases, all must be handled |
if let P = x | No | No | One case, ignore the rest |
if let ... else | No | No | Two cases without nesting |
let ... else | No | No (diverges) | Extract or bail out early |
while let P = x | No | No | Loop while the pattern matches |
matches!(x, P) | No | bool | Test a pattern in a condition |
x.is_some_and(f) | No | bool | Test the inner value of Option |
| Pattern | Matches | Binds |
|---|---|---|
Some(x) | The Some variant | Inner value |
Point { x, y } | A struct with both fields | Fields by name |
Point { x, .. } | A struct with at least x | x only |
(a, b) | A two-element tuple | Both elements |
[first, .., last] | A slice with at least two items | Ends only |
n @ 1..=9 | A number in range | n |
1 | 2 | 3 | Any of the alternatives | Nothing |
_ | Anything | Nothing |
&Some(x) | A reference to Some | x by copy/ref per ergonomics |
Practical edge cases and deep dives
1. Exhaustiveness breaks when someone else adds a variant
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
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:
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
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
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 validmatch 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
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
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.
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.
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
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 / symptom | Cause | Fix |
|---|---|---|
E0004 non-exhaustive patterns | Missing variant, or coverage relies on guards | Add the missing arm or an unguarded fallback |
unreachable_patterns warning | Earlier arm already covers it | Reorder or remove |
E0382 use of moved value after a match | Arm moved the scrutinee | Match &value or value.as_ref() |
E0507 cannot move out of borrowed content | Pattern moves from a reference | Bind by reference |
E0308 mismatched types in guards | Comparing &str with String | Compare s == "x" or s.as_str() |
| Arm never runs | _ placed before it | Move _ last |
let Some(x) = opt; compiles with a warning | let with a non-irrefutable pattern | Use let ... else or if let |
E0005 refutable pattern in local binding | Same as above, newer compiler phrasing | let ... else |
match on a float fails to compile | Floats are not structural-match | Compare ranges with guards |
| Enum grows, match silently wrong | Wildcard used on an owned enum | Remove the wildcard |
| Borrow error inside one arm | Arm holds a borrow across a move | Scope the borrow, split the arms |
Try matching browser tools
All toolsSmall utilities that fit Rust work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Rust guides
All Rust guidesRust Unsafe: Raw Pointers, FFI Bindings, and Soundness Invariants
What unsafe actually unlocks, the five soundness contracts behind raw pointers, and the FFI rules for repr(C), CString and unwinding.
Rust Pin and Unpin: Memory Pinning, Self-Referential Structs, and Futures
Why a future must not move after polling starts, what Unpin opts out of, and how Box::pin, pin! and map_unchecked_mut express that guarantee.
Rust Arrays and Slices: Fixed Arrays, &[T] Fat Pointers, and DSTs
An array carries its length in its type; a slice carries it in the pointer. The split_at_mut, chunks and TryFrom patterns that follow from that.
Rust Macros: macro_rules! Patterns, Hygiene, and Procedural Macros
Matcher fragments, repetition, hygiene and the proc-macro crate. How to read a macro_rules! error and when a derive macro is the right tool.
More in Rust
All Rust guidesThe guides filed next to this one in Rust, in library order.