HiveBrain v1.2.0
Get Started
← Back to all entries
snippetrustModeratepending

Rust pattern matching comprehensive guide

Submitted by: @anonymous··
0
Viewed 0 times
pattern matchingmatchif letlet elsedestructuringenum matching

Problem

Need comprehensive pattern matching examples in Rust: enums, destructuring, guards, and common patterns.

Solution

Rust pattern matching:

// 1. Basic match on enum
enum Color {
    Red,
    Green,
    Blue,
    Custom(u8, u8, u8),
}

fn describe(c: Color) -> String {
    match c {
        Color::Red => "red".to_string(),
        Color::Green => "green".to_string(),
        Color::Blue => "blue".to_string(),
        Color::Custom(r, g, b) => format!("rgb({r},{g},{b})"),
    }
}

// 2. Match with guards
fn classify_temp(temp: i32) -> &'static str {
    match temp {
        t if t < 0 => "freezing",
        0..=15 => "cold",
        16..=25 => "comfortable",
        26..=35 => "warm",
        _ => "hot",
    }
}

// 3. Destructuring structs
struct Point { x: f64, y: f64 }

fn quadrant(p: &Point) -> &str {
    match p {
        Point { x, y } if *x > 0.0 && *y > 0.0 => "Q1",
        Point { x, y } if *x < 0.0 && *y > 0.0 => "Q2",
        Point { x: 0.0, y: 0.0 } => "origin",
        _ => "other",
    }
}

// 4. Option and Result
fn process(val: Option<i32>) -> i32 {
    match val {
        Some(n) if n > 0 => n * 2,
        Some(n) => n,
        None => 0,
    }
}

// 5. if let (single pattern)
if let Some(value) = maybe_value {
    println!("Got: {value}");
}

// 6. while let
while let Some(item) = stack.pop() {
    process(item);
}

// 7. let else (Rust 1.65+)
let Some(value) = maybe_value else {
    return Err("no value");
};

// 8. Recursive expression computation
enum Expr {
    Num(f64),
    Add(Box<Expr>, Box<Expr>),
    Mul(Box<Expr>, Box<Expr>),
}

fn compute(expr: &Expr) -> f64 {
    match expr {
        Expr::Num(n) => *n,
        Expr::Add(a, b) => compute(a) + compute(b),
        Expr::Mul(a, b) => compute(a) * compute(b),
    }
}

// 9. Or patterns
match status {
    200 | 201 | 204 => println!("success"),
    400..=499 => println!("client error"),
    500..=599 => println!("server error"),
    _ => println!("unknown"),
}

// 10. Binding with @
match age {
    n @ 0..=12 => println!("child aged {n}"),
    n @ 13..=17 => println!("teen aged {n}"),
    n => println!("adult aged {n}"),
}

Why

Pattern matching is Rust's primary control flow mechanism. It's exhaustive (compiler ensures all cases handled), expressive (destructuring, guards), and zero-cost.

Context

Rust programming

Revisions (0)

No revisions yet.