0
0
Rustprogramming~5 mins

Basic match usage in Rust

Choose your learning style9 modes available
Introduction

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

You want to do different things based on a number or word.
You have a small set of options and want to handle each one clearly.
You want to replace many <code>if-else</code> checks with cleaner code.
You want to handle errors or special cases in a clear way.
You want to check the type or value of something and act accordingly.
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 underscore _ means "anything else" (default case).

Examples
Checks the number and prints the matching word.
Rust
let number = 3;
match number {
    1 => println!("One"),
    2 => println!("Two"),
    3 => println!("Three"),
    _ => println!("Other number"),
}
Matches if the letter is a vowel or not.
Rust
let letter = 'a';
match letter {
    'a' | 'e' | 'i' | 'o' | 'u' => println!("Vowel"),
    _ => println!("Consonant"),
}
Uses a range pattern to check if x is between 1 and 5.
Rust
let x = 5;
match x {
    1..=5 => println!("Between 1 and 5"),
    _ => println!("Outside range"),
}
Sample Program

This program checks the number in day and prints the matching weekday name. If the number is not 1 to 7, it prints "Invalid day".

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

Every possible value should be covered by patterns or the default _ case, or the code will not compile.

You can match many patterns in one line using | (OR) operator.

Match arms can run any code, not just print statements.

Summary

match checks a value against many patterns.

Use _ to catch all other cases.

It makes your code easier to read and safer.