Using Rust Match Guards

RustRustBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we learn about using match guards in Rust to filter arms based on conditions. The match guard is added after the pattern and is represented by the if keyword followed by a condition. The guard condition allows us to further refine the matching of patterns and perform additional checks before executing the corresponding arm of the match expression. However, it is important to note that the compiler does not consider guard conditions when checking pattern coverage, so it's necessary to ensure that all patterns are still covered by the match expression.

Note: If the lab does not specify a file name, you can use any file name you want. For example, you can use main.rs, compile and run it with rustc main.rs && ./main.

Guards

A match guard can be added to filter the arm.

#[allow(dead_code)]
enum Temperature {
    Celsius(i32),
    Fahrenheit(i32),
}

fn main() {
    let temperature = Temperature::Celsius(35);
    // ^ TODO try different values for `temperature`

    match temperature {
        Temperature::Celsius(t) if t > 30 => println!("{}C is above 30 Celsius", t),
        // The `if condition` part ^ is a guard
        Temperature::Celsius(t) => println!("{}C is below 30 Celsius", t),

        Temperature::Fahrenheit(t) if t > 86 => println!("{}F is above 86 Fahrenheit", t),
        Temperature::Fahrenheit(t) => println!("{}F is below 86 Fahrenheit", t),
    }
}

Note that the compiler won't take guard conditions into account when checking if all patterns are covered by the match expression.

fn main() {
    let number: u8 = 4;

    match number {
        i if i == 0 => println!("Zero"),
        i if i > 0 => println!("Greater than zero"),
        // _ => unreachable!("Should never happen."),
        // TODO ^ uncomment to fix compilation
    }
}

Summary

Congratulations! You have completed the Guards lab. You can practice more labs in LabEx to improve your skills.

Other Rust Tutorials you may like