0
0
Rustprogramming~5 mins

Match overview in Rust

Choose your learning style9 modes available
Introduction

The match expression helps you check a value against many possibilities and run code based on which one fits. It makes your code clear and easy to read.

When you want to do different things based on different values of a variable.
When you have a few fixed options and want to handle each one clearly.
When you want to replace many <code>if-else</code> checks with cleaner code.
When you want to make sure you cover all possible cases of a value.
When you want to extract data from complex values and use it.
Syntax
Rust
match value {
    pattern1 => expression1,
    pattern2 => expression2,
    _ => default_expression,
}

The value is what you want to check.

Each pattern is a possible match. The arrow => points to the code to run if it matches.

Examples
This checks the number and prints its name or "Other number" if no match.
Rust
let number = 3;
match number {
    1 => println!("One"),
    2 => println!("Two"),
    3 => println!("Three"),
    _ => println!("Other number"),
}
This matches string values and prints a message for each color.
Rust
let color = "red";
match color {
    "red" => println!("Stop"),
    "green" => println!("Go"),
    "yellow" => println!("Slow down"),
    _ => println!("Unknown color"),
}
This matches enum variants and prints a direction message.
Rust
enum Direction {
    North,
    South,
    East,
    West,
}

let dir = Direction::East;
match dir {
    Direction::North => println!("Going up"),
    Direction::South => println!("Going down"),
    Direction::East => println!("Going right"),
    Direction::West => println!("Going left"),
}
Sample Program

This program uses match to find the name of the day from its number and prints it.

Rust
fn main() {
    let day = 3;
    let day_name = match day {
        1 => "Monday",
        2 => "Tuesday",
        3 => "Wednesday",
        4 => "Thursday",
        5 => "Friday",
        6 => "Saturday",
        7 => "Sunday",
        _ => "Invalid day",
    };
    println!("Day {} is {}", day, day_name);
}
OutputSuccess
Important Notes

The _ pattern is a catch-all for any value not matched earlier.

Each match arm must return the same type if you use match as an expression.

You can match complex patterns like enums, tuples, and even use guards for extra checks.

Summary

Match checks a value against many patterns clearly.

It helps replace many if-else statements with cleaner code.

Always include a catch-all _ to handle unexpected cases.