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 arm is selected. Otherwise, pattern matching continues to the next arm.
167
+
168
+
r[expr.match.if.let.guard.behavior]
169
+
When the pattern matches successfully, the `if let` expression in the guard is evaluated:
170
+
* If the inner pattern (`subpattern`) matches the result of `guard_expr`, the guard evaluates to `true`.
* The `if let` guard may refer to variables bound by the outer match pattern.
185
+
* New variables bound inside the `if let` guard (e.g., `y` in the example above) are available within the body of the match arm where the guard evaluates to `true`, but are not accessible in other arms or outside the match expression.
186
+
187
+
```rust
188
+
letopt=Some(42);
189
+
190
+
matchopt {
191
+
Some(x) ifletSome(y) =Some(x+1) => {
192
+
// Both `x` and `y` are available in this arm,
193
+
// since the pattern matched and the guard evaluated to true.
194
+
println!("x = {}, y = {}", x, y);
195
+
}
196
+
_=> {
197
+
// `y` is not available here --- it was only bound inside the guard above.
198
+
// Uncommenting the line below will cause a compile-time error:
199
+
// println!("{}", y); // error: cannot find value `y` in this scope
200
+
}
201
+
}
202
+
203
+
// Outside the match expression, neither `x` nor `y` are in scope.
204
+
```
205
+
206
+
* The outer pattern variables (`x`) follow the same borrowing behavior as in standard match guards (see below).
207
+
208
+
r[expr.match.if.let.guard.borrowing]
209
+
Before a guard (including an `if let` guard) is evaluated:
210
+
1. Pattern bindings are performed first
211
+
Variables from the outer match pattern (e.g., `x` in `Some(x)`) are bound and initialized. These bindings may involve moving, copying, or borrowing values from the scrutinee.
212
+
```rust
213
+
matchSome(String::from("hello")) {
214
+
Some(s) if/* guard */=> { /* s is moved here */ }
215
+
_=> {}
216
+
}
217
+
```
218
+
2.Guardevaluationhappensafterthat, and:
219
+
*Itrunsusingasharedborrowofthescrutinee
220
+
*Youcannotmovefromthescrutineeinsidetheguard.
221
+
*Newbindingscreatedinsidetheguard (e.g., via `ifletSome(y) =expr`) arelocaltotheguardanddonotpersistintothematcharmbody.
222
+
```rust
223
+
letval=Some(vec![1, 2, 3]);
224
+
225
+
letresult=matchval {
226
+
Some(v) ifletSome(_) =take(v) =>"ok", // ERROR: cannot move out of `v`
0 commit comments