Skip to main content
A match guard is an additional if condition appended to a match arm pattern that must evaluate to true for that specific arm to execute. It allows for arbitrary boolean expressions to refine pattern matching beyond standard structural destructuring.

Evaluation Mechanics

When a match statement executes, the compiler evaluates arms sequentially. For an arm containing a match guard:
  1. The compiler first checks if the value structurally matches the pattern.
  2. If the structural match succeeds, any variables defined in the pattern are bound.
  3. The boolean_expression (the guard) is then evaluated using those bound variables.
  4. If the guard evaluates to true, the result_expression executes.
  5. If the guard evaluates to false, the binding is discarded, and the compiler proceeds to evaluate the next match arm.

Exhaustiveness Checking

The Rust compiler’s exhaustiveness checker ignores match guards. Because the compiler cannot statically determine if an arbitrary runtime boolean expression will evaluate to true, a pattern equipped with a match guard does not count toward making a match exhaustive. Even if a guard logically covers all possibilities, the compiler requires a fallback arm (an identical pattern without a guard, or a catch-all like _) to guarantee exhaustiveness.

Interaction with Compound Patterns

When a match guard is used alongside the pattern OR operator (|), the guard applies to the entire compound pattern, not just the pattern immediately preceding the if keyword. The syntax behaves as (Pattern1 | Pattern2) if condition, rather than Pattern1 | (Pattern2 if condition).

Variable Shadowing

Variables bound in the pattern of a match guard shadow variables of the same name in the outer scope. The match guard evaluates within the scope of the newly bound variables, not the outer variables.
Tired of Poor Rust Skills? Fix That With Deep Grasping!Learn More