liveBook · Manning

Guard

As explained in Learn Rust in a Month of Lunches

A match guard is an additional Boolean condition attached to a Rust match arm after its pattern matches.

A match guard adds an extra Boolean condition to a match arm. Rust checks the pattern first, then uses the guard to decide whether that arm applies. Write the condition after the pattern with if. section 3.2.2

Checking two conditions

Here, the tuple pattern binds children and married, while each guard narrows the case: `(children, married) if !married` handles unmarried people, and `if children == 0 && married` handles married people without children. If neither guard succeeds, the `_` arm runs. section 3.2.2

Keep these match-guard behaviors in mind:

  • Use a Boolean expression after `if`; a variable can test true directly, while `!variable` tests false. section 3.2.2
  • Order arms deliberately: matching stops at the first arm whose pattern and guard succeed. section 3.2.2
  • A macro can make a guard optional, as in `matches!(9, 9 if ALLOWS_TRUE)`, where the guard can turn an otherwise matching pattern into false. section 22.3
macro_rules! matches {
    ($expression:expr, $pattern:pat $(if $guard:expr)? $(,)?) => {
        match $expression {
            $pattern $(if $guard)? => true,
            _ => false
        }
    };
}

Browse the macro pattern that accepts an optional guard and places it directly on the generated match arm. section 22.3

How Learn Rust in a Month of Lunches covers it

How deep it goes
Explains syntax, Boolean shorthand, arm ordering, and optional macro expansion without descending into compiler internals.
Examples
Uses married-and-children tuples, color tuples, and a matches! macro with a constant Boolean guard.
What it assumes
Assumes basic match syntax, patterns, tuples, variables, and Boolean operators while teaching guard syntax directly.
What you can do after
Apply match guards to select arms using additional Boolean conditions and recognize why later arms may not run.
How it connects
Connects match statements with patterns, Boolean expressions, tuples, and macro_rules! macros.

Also explained in

Compare how 4 books explain guard →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Rust in a Month of Lunches. The section links point to the parts of the book it draws on.