Pattern Matching with match
match compares a value against patterns, binding variables and running the first matching arm. Compiler enforces exhaustiveness.
Busca en todas las páginas de la documentación
match compares a value against patterns, binding variables and running the first matching arm. Compiler enforces exhaustiveness.
enum Color { Red, Green, Blue }
fn label(c: Color) -> &'static str {
match c {
Color::Red => "red",
Color::Green => "green",
Color::Blue => "blue",
}
}When to reach for this: Enums, Option/Result, parsing tokens, and multi-way branching with destructuring.
#[derive(Debug)]
enum Token { Num(i64), Ident(String), Eof }
fn eval(tok: Token) -> String {
match tok {
Token::Num(n) if n < 0 => format!("negative {n}"),
Token::Num(n) => n.to_string(),
Token::Ident(name) => name,
Token::Eof => "eof".into(),
}
}
fn main() {
println!("{}", eval(Token::Num(-3)));
}What this demonstrates:
n, name from variant payloadsif n < 0 refines match armmatch as expression returning String1..=5Point { x, y }@ bindings n @ 1..=100| or-patterns Some(0) | Some(1)match vs if letmatch handles many patterns; if let one pattern ergonomically.
mut binding modes affect move/copy. Fix: Read edition migration guide for ref/mut patterns.match x: u8 needs _ arm. Fix: Add wildcard or ranges.ref pattern. Fix: Use ref/ref mut to borrow fields.if let chain.| Alternative | Use When | Don't Use When |
|---|---|---|
if let / while let | Single pattern | Many variants |
matches! macro | Boolean test | Need bound values |
let-else | Early return on mismatch | Complex multi-arm logic |
if chain | Simple scalars | Enum with data |
Stack versions: This page was written for Rust 1.97.0 (edition 2024), Tokio 1.x, Axum 0.8, serde 1.0, sqlx 0.8, clap 4, and Polars 0.46+.
Revisado por Chris St. John·Última actualización: 16 jul 2026