Rust Match

Pattern matching for control flow in Rust

🔍 What is Match in Rust?

Match is Rust's powerful pattern matching feature that compares values against patterns and executes code based on matches. It's like a super-powered switch statement that ensures all cases are handled.


// Basic match example
let number = 3;

match number {
    1 => println!("One"),
    2 => println!("Two"),
    3 => println!("Three"),
    _ => println!("Something else"),
}
                                    

Output:

Three

Match Patterns

🎯

Exact Values

Match specific values directly

match x {
    1 => "one",
    2 => "two",
    _ => "other",
}
📊

Ranges

Match ranges of values

match age {
    0..=12 => "child",
    13..=19 => "teen",
    _ => "adult",
}
🔧

Enums

Match enum variants

match result {
    Ok(value) => value,
    Err(_) => 0,
}
🌟

Guards

Add conditions to patterns

match x {
    n if n > 0 => "positive",
    0 => "zero",
    _ => "negative",
}

🔹 Basic Match Syntax

Match expressions compare a value against patterns:

fn main() {
    let coin = "quarter";
    
    let value = match coin {
        "penny" => 1,
        "nickel" => 5,
        "dime" => 10,
        "quarter" => 25,
        _ => 0, // catch-all pattern
    };
    
    println!("Value: {} cents", value);
}

Output:

Value: 25 cents

🔹 Matching with Option

Match is perfect for handling Option types:

fn main() {
    let maybe_number = Some(42);
    
    match maybe_number {
        Some(value) => println!("Got a value: {}", value),
        None => println!("No value found"),
    }
    
    // Using match in a function
    let result = match maybe_number {
        Some(n) => n * 2,
        None => 0,
    };
    
    println!("Result: {}", result);
}

Output:

Got a value: 42
Result: 84

🔹 Multiple Patterns

You can match multiple patterns in one arm:

fn main() {
    let day = "Saturday";
    
    let day_type = match day {
        "Monday" | "Tuesday" | "Wednesday" | "Thursday" | "Friday" => "Weekday",
        "Saturday" | "Sunday" => "Weekend",
        _ => "Unknown",
    };
    
    println!("{} is a {}", day, day_type);
}

Output:

Saturday is a Weekend

🧠 Test Your Knowledge

What does the _ pattern do in a match expression?