An Or pattern in Rust is a structural matching construct denoted by the pipe operator (Documentation Index
Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt
Use this file to discover all available pages before exploring further.
|) that allows a single pattern-matching arm to evaluate against multiple alternative patterns. If the scrutinized value matches any of the specified alternatives, the overall pattern match succeeds.
Core Mechanics and Evaluation
Or patterns evaluate strictly from left to right. The compiler utilizes short-circuit evaluation; the first alternative that successfully matches the scrutinized value terminates the pattern evaluation, and the associated code block is executed. While Or patterns are valid in any pattern-matching context (includingmatch, if let, and while let), their use in let statements and function parameters carries a strict irrefutability requirement. Because let bindings and function parameters cannot handle match failures, the Or pattern used in these contexts must be irrefutable (guaranteed to match all possible values of the type). Most Or patterns, such as matching specific integers, are refutable and will cause a compile-time error in these contexts.
Variable Binding Uniformity
The most strict compiler constraint regarding Or patterns is binding uniformity. If an Or pattern binds variables to extract data from the scrutinized value, every alternative within that Or pattern must bind the exact same set of variables. Furthermore, the bound variables must resolve to the exact same type and utilize the exact same binding mode (mut, ref, ref mut, or by value) across all alternatives.
- Failing to bind the same variables yields
E0408: variable is not bound in all patterns. - Using different binding modes yields
E0409: variable is bound inconsistently.
Nested Or Patterns
Or patterns can be nested arbitrarily deep within other structural patterns (such as tuples, slices, structs, or enum variants). You do not need to duplicate the outer structure to match against multiple inner values.Precedence and Grouping
The| operator has low precedence in pattern syntax. When combining Or patterns with other pattern features, such as range patterns (..=) or reference modifiers (&, ref), the Or pattern applies to the entire pattern on either side of the pipe.
Parentheses must be used to explicitly group Or patterns to control precedence and restrict the scope of the alternation.
Master Rust with Deep Grasping Methodology!Learn More





