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.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL rust(("`Rust`")) -.-> rust/BasicConceptsGroup(["`Basic Concepts`"]) rust(("`Rust`")) -.-> rust/DataTypesGroup(["`Data Types`"]) rust(("`Rust`")) -.-> rust/ControlStructuresGroup(["`Control Structures`"]) rust(("`Rust`")) -.-> rust/FunctionsandClosuresGroup(["`Functions and Closures`"]) rust(("`Rust`")) -.-> rust/DataStructuresandEnumsGroup(["`Data Structures and Enums`"]) rust(("`Rust`")) -.-> rust/ErrorHandlingandDebuggingGroup(["`Error Handling and Debugging`"]) rust/BasicConceptsGroup -.-> rust/variable_declarations("`Variable Declarations`") rust/DataTypesGroup -.-> rust/integer_types("`Integer Types`") rust/DataTypesGroup -.-> rust/string_type("`String Type`") rust/ControlStructuresGroup -.-> rust/pattern_matching("`Pattern Matching`") rust/FunctionsandClosuresGroup -.-> rust/function_syntax("`Function Syntax`") rust/FunctionsandClosuresGroup -.-> rust/expressions_statements("`Expressions and Statements`") rust/DataStructuresandEnumsGroup -.-> rust/struct_instantiate("`Struct Instantiation`") rust/DataStructuresandEnumsGroup -.-> rust/method_syntax("`Method Syntax`") rust/DataStructuresandEnumsGroup -.-> rust/match_operator("`match Operator`") rust/ErrorHandlingandDebuggingGroup -.-> rust/error_propagation("`Error Propagation`") subgraph Lab Skills rust/variable_declarations -.-> lab-99315{{"`Using Rust Match Guards`"}} rust/integer_types -.-> lab-99315{{"`Using Rust Match Guards`"}} rust/string_type -.-> lab-99315{{"`Using Rust Match Guards`"}} rust/pattern_matching -.-> lab-99315{{"`Using Rust Match Guards`"}} rust/function_syntax -.-> lab-99315{{"`Using Rust Match Guards`"}} rust/expressions_statements -.-> lab-99315{{"`Using Rust Match Guards`"}} rust/struct_instantiate -.-> lab-99315{{"`Using Rust Match Guards`"}} rust/method_syntax -.-> lab-99315{{"`Using Rust Match Guards`"}} rust/match_operator -.-> lab-99315{{"`Using Rust Match Guards`"}} rust/error_propagation -.-> lab-99315{{"`Using Rust Match Guards`"}} end

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