You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Here, `guard_expr` is evaluated and matched against `subpattern`. If the match succeeds, the guard evaluates to `true`and the armis selected. Otherwise, pattern matching continues to the next arm.
168
+
Here, `guard_expr` is evaluated and matched against `subpattern`. If the `if let` expression in the guard matches successfully and the arm’s body is executed. Otherwise, pattern matching continues to the next arm.
166
169
167
170
r[expr.match.if.let.guard.behavior]
168
171
When the pattern matches successfully, the `if let` expression in the guard is evaluated:
169
-
*If the inner pattern (`subpattern`) matches the result of `guard_expr`, the guard evaluates to `true`.
172
+
*The guard proceeds if the inner pattern (`subpattern`) matches the result of `guard_expr`.
170
173
* Otherwise, the next arm is tested.
171
174
172
175
```rust,ignore
@@ -176,7 +179,6 @@ let msg = match value {
176
179
Some(x) if let Some(y) = Some(x - 1) => format!("Matched inner value: {}", y),
177
180
_ => "No match".to_string(),
178
181
};
179
-
180
182
```
181
183
182
184
r[expr.match.if.let.guard.scope]
@@ -225,14 +227,13 @@ Before a guard (including an `if let` guard) is evaluated:
225
227
Some(v) if let Some(_) = take(v) => "ok", // ERROR: cannot move out of `v`
226
228
_ => "nope",
227
229
};
228
-
229
230
```
230
231
In the above example, `v` is already bound in the outer pattern, and the guard attempts to move it --- this is not allowed. You can fix it by cloning or borrowing:
231
232
```rust,ignore
232
233
Some(v) if let Some(_) = take(v.clone()) => "ok",
233
234
```
234
235
> [!NOTE]
235
-
> Unlike regular if guards, `if let` guards execute only once per match arm, even if the pattern uses the `|` operator to match multiple patterns. This avoids repeated evaluation and potential side effects.
236
+
> Multiple matches using the `|` operator can cause the pattern guard and the side effects it has to execute multiple times. For example:
236
237
> ```rust,ignore
237
238
> use std::cell::Cell;
238
239
>
@@ -241,7 +242,7 @@ Before a guard (including an `if let` guard) is evaluated:
241
242
> 1 | _ if let Some(_) = { i.set(i.get() + 1); Some(1) } => {}
242
243
> _ => {}
243
244
> }
244
-
> assert_eq!(i.get(), 1); // Guard not executed twice
245
+
> assert_eq!(i.get(), 2); // Guard is executed twice
0 commit comments