Rust

match with Guards, Ranges, and Bindings

admin by @admin ADMIN
5d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
`match` arms can have `if` guards, range patterns (`1..=5`), bindings (`x @ pattern`), and ORs (`A | B`). Combine them for very expressive dispatch.
Rust
Raw
fn classify(n: i32) -> &'static str {
    match n {
        0                     => "zero",
        1..=9                 => "single digit",
        10..=99               => "double digit",
        n if n < 0            => "negative",
        n if n % 2 == 0       => "even big number",
        _                     => "odd big number",
    }
}

fn describe(opt: Option<i32>) -> String {
    match opt {
        Some(x @ 1..=10)  => format!("small Some: {x}"),
        Some(x) if x > 100 => format!("big Some: {x}"),
        Some(x)           => format!("normal Some: {x}"),
        None              => "nothing".into(),
    }
}

fn main() {
    for n in [-3, 0, 7, 42, 105, 200] { println!("{n}: {}", classify(n)); }
    println!("{}", describe(Some(5)));      // small Some: 5
    println!("{}", describe(Some(500)));    // big Some: 500
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.