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



