Rust Tutorial · Structs, Enums and Collections · Lesson 15 of 29

Rust Pattern Matching

Use match, if let, let else and let chains to destructure values and handle cases exhaustively.

Create a free account to save this page, take notes and track your progress. Sign in

match

match must cover every possible value (the compiler checks), and patterns can include ranges, multiple values and guards (if conditions).

match with ranges and guards
fn classify(status: u16) -> &'static str {
    match status {
        200 | 201 | 204 => "success",
        300..=399 => "redirect",
        404 => "not found",
        code if code >= 500 => "server error",
        _ => "client error",
    }
}

fn main() {
    for code in [200, 301, 404, 418, 503] {
        println!("{code}: {}", classify(code));
    }
}

Output

200: success
301: redirect
404: not found
418: client error
503: server error

Run this on your computer — see “Get Started” for setup.

if let, let else and let chains

  • if let Some(x) = value { ... } handles one pattern.
  • let Some(x) = value else { return ... }; unwraps or exits early.
  • Let chains (Rust 2024 edition) combine patterns and conditions: if let Some(u) = user && u.active { ... }.
let else and let chains
struct User { name: String, active: bool }

fn greeting(user: Option<&User>) -> String {
    let Some(user) = user else {
        return "Hello, guest".to_string();
    };
    format!("Hello, {}", user.name)
}

fn main() {
    let ana = User { name: "Ana".into(), active: true };
    println!("{}", greeting(Some(&ana)));
    println!("{}", greeting(None));
    let maybe_user = Some(&ana);
    if let Some(u) = maybe_user && u.active {
        println!("{} is active", u.name);
    }
}

Output

Hello, Ana
Hello, guest
Ana is active

Run this on your computer — see “Get Started” for setup.

Test yourself

What happens if a match doesn't cover every case?

  1. It panics at runtime
  2. The program doesn't compile
  3. Nothing happens for missing cases
  4. A warning is printed
Show answer

Answer: The program doesn't compile

Was this page helpful?