Abstract

Pattern matching is Rust’s most expressive control-flow tool. Once you stop reaching for if/else chains, a lot of code gets both shorter and safer. This is a quick tour with runnable examples.

The basics: match

enum Command {
    Up(u32),
    Down(u32),
    Stop,
}

fn apply(cmd: Command) -> &'static str {
    match cmd {
        Command::Up(n) => "went up",
        Command::Down(n) => "went down",
        Command::Stop => "stopped",
    }
}

Two things matter here: match is exhaustive (the compiler forces you to handle every variant), and patterns can bind values (n in the first two arms).

Destructuring

Patterns destructure the data they match:

struct Point { x: i32, y: i32 }

fn sum(p: Point) -> i32 {
    match p {
        Point { x, y } => x + y,
    }
}

fn sum_pair(pair: (i32, i32)) -> i32 {
    match pair {
        (x, y) => x + y,
    }
}

You can also destructure references with ref or match through a reference:

let p = Point { x: 3, y: 4 };
match &p {
    Point { x, y } => println!("{x}, {y}"), // x and y are &i32 here
}

Guards

Add a when-style condition with a guard:

match cmd {
    Command::Up(n) if n > 10 => "big step up",
    Command::Up(_)          => "small step up",
    _                       => "something else",
}

_ is the catch-all wildcard, and _ ignores a value entirely.

Multiple patterns and ranges

fn grade(n: u32) -> &'static str {
    match n {
        90..=100 => "A",
        80..=89  => "B",
        70..=79  => "C",
        _        => "F",
    }
}

if let and while let

When you only care about one pattern, match is verbose:

let value: Option<i32> = Some(7);

// match version
match value {
    Some(x) => println!("{x}"),
    None => {}
}

// if let version
if let Some(x) = value {
    println!("{x}");
}

while let keeps looping while a pattern still matches:

let mut stack = vec![1, 2, 3];
while let Some(top) = stack.pop() {
    println!("{top}");
}

Why this beats if chains

The compiler checks exhaustiveness, so adding a variant to an enum later forces you to revisit every match over it. That’s a feature: the compiler finds the code paths you forgot, which is exactly the kind of bug if/else lets through silently.

Next time you write a chain of if/else if, try expressing the same logic as a match — the result is usually clearer.