0
0
Rustprogramming~5 mins

Match guards in Rust

Choose your learning style9 modes available
Introduction

Match guards help you add extra checks to patterns in a match statement. They let you be more specific about when a pattern should be used.

You want to match a value only if it meets a certain condition, like being greater than 10.
You have multiple similar patterns but want to handle them differently based on extra rules.
You want to avoid writing nested if statements inside match arms.
You want clearer and cleaner code by combining pattern matching and conditions.
You want to check a variable's value and another condition at the same time.
Syntax
Rust
match value {
    pattern if condition => {
        // code to run if pattern matches and condition is true
    },
    _ => {
        // code for other cases
    }
}

The if condition after a pattern is called a match guard.

The guard must be a boolean expression that decides if the match arm runs.

Examples
This matches any number greater than 0 and prints it. Otherwise, it prints "Not positive".
Rust
let num = 5;
match num {
    x if x > 0 => println!("Positive number: {}", x),
    _ => println!("Not positive"),
}
This matches if the character is a letter using a guard.
Rust
let ch = 'a';
match ch {
    c if c.is_alphabetic() => println!("Letter: {}", c),
    _ => println!("Not a letter"),
}
This matches pairs where both numbers are equal using a guard, otherwise prints different pairs.
Rust
let pair = (2, 3);
match pair {
    (x, y) if x == y => println!("Equal pair: ({}, {})", x, y),
    (x, y) => println!("Different pair: ({}, {})", x, y),
}
Sample Program

This program checks if a number is even or odd using match guards. It prints the result accordingly.

Rust
fn main() {
    let number = 7;
    match number {
        n if n % 2 == 0 => println!("{} is even", n),
        n if n % 2 != 0 => println!("{} is odd", n),
    }
}
OutputSuccess
Important Notes

Match guards run after the pattern matches but before the arm executes.

If the guard condition is false, Rust continues checking other patterns.

Guards help keep your match statements clean and expressive.

Summary

Match guards add extra conditions to patterns in a match.

They let you check values more precisely without nested ifs.

Use if condition after a pattern to add a guard.