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.
186
+
* 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.
187
+
188
+
```rust
189
+
#![feature(if_let_guard)]
190
+
191
+
letopt=Some(42);
192
+
193
+
matchopt {
194
+
Some(x) ifletSome(y) =Some(x+1) => {
195
+
// Both `x` and `y` are available in this arm,
196
+
// since the pattern matched and the guard evaluated to true.
197
+
println!("x = {}, y = {}", x, y);
198
+
}
199
+
_=> {
200
+
// `y` is not available here — it was only bound inside the guard above.
201
+
// Uncommenting the line below will cause a compile-time error:
202
+
// println!("{}", y); // error: cannot find value `y` in this scope
203
+
}
204
+
}
205
+
206
+
// Outside the match expression, neither `x` nor `y` are in scope.
207
+
```
208
+
209
+
* The outer pattern variables (`x`) follow the same borrowing behavior as in standard match guards (see below).
210
+
211
+
r[expr.match.if.let.guard.borrowing]
212
+
Before a guard (including an `if let` guard) is evaluated:
213
+
1. Pattern bindings are performed first
214
+
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.
215
+
```rust
216
+
matchSome(String::from("hello")) {
217
+
Some(s) if/* guard */=> { /* s is moved here */ }
218
+
_=> {}
219
+
}
220
+
```
221
+
2.Guardevaluationhappensafterthat, and:
222
+
*Itrunsusingasharedborrowofthescrutinee
223
+
*Youcannotmovefromthescrutineeinsidetheguard.
224
+
*Newbindingscreatedinsidetheguard (e.g., via `ifletSome(y) =expr`) arelocaltotheguardanddonotpersistintothematcharmbody.
225
+
```rust
226
+
#![feature(if_let_guard)]
227
+
228
+
letval=Some(vec![1, 2, 3]);
229
+
230
+
letresult=matchval {
231
+
Some(v) ifletSome(_) =take(v) =>"ok", // ERROR: cannot move out of `v`
0 commit comments