@@ -62,7 +62,8 @@ match x {
62
62
Variables bound within the pattern are scoped to the match guard and the arm's
63
63
expression. The [ binding mode] (move, copy, or reference) depends on the pattern.
64
64
65
- Multiple match patterns may be joined with the ` | ` operator:
65
+ Multiple match patterns may be joined with the ` | ` operator. Each pattern will be
66
+ tested in left-to-right sequence until a successful match is found.
66
67
67
68
``` rust
68
69
# let x = 9 ;
@@ -73,19 +74,30 @@ let message = match x {
73
74
};
74
75
75
76
assert_eq! (message , " a few" );
77
+
78
+ // Demonstration of pattern match order.
79
+ struct S (i32 , i32 );
80
+
81
+ match S (1 , 2 ) {
82
+ S (z @ 1 , _ ) | S (_ , z @ 2 ) => assert_eq! (z , 1 ),
83
+ _ => panic! (),
84
+ }
76
85
```
77
86
78
- Please notice that the ` 2..=9 ` is a [ Range Pattern] , not a [ Range Expression]
79
- and, thus, only those types of ranges supported by range patterns can be used
80
- in match arms.
87
+ > Note: The ` 2..=9 ` is a [ Range Pattern] , not a [ Range Expression] . Thus, only
88
+ > those types of ranges supported by range patterns can be used in match arms.
89
+
90
+ Every binding in each ` | ` separated pattern must appear in all of the patterns
91
+ in the arm. Every binding of the same name must have the same type, and have
92
+ the same binding mode.
81
93
82
94
Match arms can accept _ match guards_ to further refine the
83
95
criteria for matching a case. Pattern guards appear after the pattern and
84
96
consist of a bool-typed expression following the ` if ` keyword. A pattern guard
85
97
may refer to the variables bound within the pattern they follow.
86
98
87
99
When the pattern matches successfully, the pattern guard expression is executed.
88
- If the expression is truthy , the pattern is successfully matched against.
100
+ If the expression evaluates to true , the pattern is successfully matched against.
89
101
Otherwise, the next pattern, including other matches with the ` | ` operator in
90
102
the same arm, is tested.
91
103
@@ -104,15 +116,13 @@ let message = match maybe_digit {
104
116
> and side effects it has to execute multiple times. For example:
105
117
>
106
118
> ``` rust
107
- > use std :: cell :: Cell ;
108
- > fn main () {
109
- > let i : Cell <i32 > = Cell :: new (0 );
110
- > match 1 {
111
- > 1 | _ if { i . set (i . get () + 1 ); false } => {}
112
- > _ => {}
113
- > }
114
- > assert_eq! (i . get (), 2 );
119
+ > # use std :: cell :: Cell ;
120
+ > let i : Cell <i32 > = Cell :: new (0 );
121
+ > match 1 {
122
+ > 1 | _ if { i . set (i . get () + 1 ); false } => {}
123
+ > _ => {}
115
124
> }
125
+ > assert_eq! (i . get (), 2 );
116
126
> ```
117
127
118
128
## Attributes on match arms
0 commit comments