A match guard is an additionalDocumentation Index
Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt
Use this file to discover all available pages before exploring further.
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 amatch statement executes, the compiler evaluates arms sequentially. For an arm containing a match guard:
- The compiler first checks if the value structurally matches the
pattern. - If the structural match succeeds, any variables defined in the pattern are bound.
- The
boolean_expression(the guard) is then evaluated using those bound variables. - If the guard evaluates to
true, theresult_expressionexecutes. - If the guard evaluates to
false, the binding is discarded, and the compiler proceeds to evaluate the nextmatcharm.
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 totrue, 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.Master Rust with Deep Grasping Methodology!Learn More





