0
0
Rustprogramming~7 mins

Match expression deep dive in Rust

Choose your learning style9 modes available
Introduction

The match expression helps you check a value against many patterns and run code based on which pattern fits. It makes your code clear and safe.

When you want to do different things based on the exact value or shape of data.
When you have multiple possible cases and want to handle each clearly.
When you want to safely unpack data inside enums or tuples.
When you want to catch all other cases with a default action.
When you want to combine conditions and bind parts of data to variables.
Syntax
Rust
match value {
    pattern1 => expression1,
    pattern2 if condition => expression2,
    pattern3 => {
        // multiple lines of code
    },
    _ => default_expression,
}

Each pattern is checked in order until one matches.

The underscore _ means "anything else" and acts like a default case.

Examples
Match a number and print if it is 1, a prime (2,3,5,7), or something else.
Rust
let number = 3;
match number {
    1 => println!("One"),
    2 | 3 | 5 | 7 => println!("Prime number"),
    _ => println!("Other number"),
}
Match a tuple and bind parts to variables to use inside the code.
Rust
let pair = (0, -2);
match pair {
    (0, y) => println!("First is zero, second is {}", y),
    (x, 0) => println!("First is {}, second is zero", x),
    _ => println!("No zeros"),
}
Use a guard if to add extra condition to a pattern.
Rust
let x = Some(5);
match x {
    Some(n) if n > 3 => println!("Big number {}", n),
    Some(n) => println!("Small number {}", n),
    None => println!("No number"),
}
Sample Program

This program matches a tuple (2, 3) against several patterns with conditions. It prints the message for the first matching case.

Rust
fn main() {
    let value = (2, 3);
    match value {
        (x, y) if x == y => println!("Both are equal: {}", x),
        (x, y) if x + y == 5 => println!("Sum is five: {} + {}", x, y),
        (x, _) if x > 0 => println!("First is positive: {}", x),
        _ => println!("No special case"),
    }
}
OutputSuccess
Important Notes

Patterns are checked top to bottom, so order matters.

Use if guards to add extra checks beyond pattern shape.

The match expression must cover all possible cases, or the code won't compile.

Summary

Match lets you compare a value to many patterns clearly.

You can bind parts of data to variables inside patterns.

Use if guards for extra conditions and _ for a default case.