Module 4 • Lesson 21

The match Expression

📚 9 min read💻 Free Course🦀 nixus.pro

The match Expression

fn main() {
    let x = 7i32;

    // Basic match - exhaustive
    let desc = match x {
        1 => "one",
        2 | 3 => "two or three",
        4..=9 => "four through nine",
        n if n < 0 => "negative",
        _ => "other",
    };
    println!("{}: {}", x, desc);

    // @ binding: test and capture
    let msg = match x {
        n @ 1..=9 => format!("single digit: {}", n),
        n => format!("multi digit: {}", n),
    };
    println!("{}", msg);

    // Matching tuples
    let point = (0, 7);
    match point {
        (0, y) => println!("on y-axis at y={}", y),
        (x, 0) => println!("on x-axis at x={}", x),
        (x, y) => println!("at ({}, {})", x, y),
    }

    // Matching with structs
    struct Point { x: i32, y: i32 }
    let p = Point { x: 5, y: 0 };
    match p {
        Point { x, y: 0 } => println!("On x-axis at {}", x),
        Point { x: 0, y } => println!("On y-axis at {}", y),
        Point { x, y }    => println!("({}, {})", x, y),
    }

    // Guards
    let pair = (2, -2);
    match pair {
        (x, y) if x == y  => println!("Equal"),
        (x, y) if x + y == 0 => println!("Sum zero"),
        (x, _) if x > 0  => println!("First positive"),
        _ => println!("Other"),
    }
}

🎯 Practice

  1. Write a function that matches a u8 (1-7) to a day name ("Monday" etc.)
  2. Match an Option<Result<i32, &str>> covering Some(Ok), Some(Err), and None cases
  3. Create a simple calculator: match (f64, char, f64) tuples for +, -, *, / operations

🎉 Key Takeaways