Skip to content

Commit ca56392

Browse files
committed
added if let guards documentation
1 parent db04a2a commit ca56392

File tree

1 file changed

+95
-0
lines changed

1 file changed

+95
-0
lines changed

src/expressions/match-expr.md

+95
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,8 @@ MatchArms ->
1818
MatchArm -> OuterAttribute* Pattern MatchArmGuard?
1919
2020
MatchArmGuard -> `if` Expression
21+
| if Expression
22+
| if let Pattern = Expression
2123
```
2224
<!-- TODO: The exception above isn't accurate, see https://github.com/rust-lang/reference/issues/569 -->
2325

@@ -150,6 +152,99 @@ This allows shared borrows to be used inside guards without moving out of the sc
150152
r[expr.match.guard.no-mutation]
151153
Moreover, by holding a shared reference while evaluating the guard, mutation inside guards is also prevented.
152154
155+
r[expr.match.if.let.guard]
156+
## If Let Guards
157+
Match arms can include `if let` guards to allow conditional pattern matching within the guard clause. This feature is currently unstable and requires the attribute. It is tracked in issue [#51114](https://github.com/rust-lang/rust/issues/51114).
158+
159+
r[expr.match.if.let.guard.syntax]
160+
```rust,ignore
161+
match expression {
162+
pattern if let subpattern = guard_expr => arm_body,
163+
...
164+
}
165+
```
166+
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`.
171+
* Otherwise, the next arm is tested.
172+
173+
```rust,ignore
174+
let value = Some(10);
175+
176+
let msg = match value {
177+
Some(x) if let Some(y) = Some(x - 1) => format!("Matched inner value: {}", y),
178+
_ => "No match".to_string(),
179+
};
180+
181+
```
182+
183+
r[expr.match.if.let.guard.scope]
184+
* 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,ignore
188+
let opt = Some(42);
189+
190+
match opt {
191+
Some(x) if let Some(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,ignore
213+
match Some(String::from("hello")) {
214+
Some(s) if /* guard */ => { /* s is moved here */ }
215+
_ => {}
216+
}
217+
```
218+
2. Guard evaluation happens after that, and:
219+
* It runs using a shared borrow of the scrutinee
220+
* You cannot move from the scrutinee inside the guard.
221+
* New bindings created inside the guard (e.g., via `if let Some(y) = expr`) are local to the guard and do not persist into the match arm body.
222+
```rust,ignore
223+
let val = Some(vec![1, 2, 3]);
224+
225+
let result = match val {
226+
Some(v) if let Some(_) = take(v) => "ok", // ERROR: cannot move out of `v`
227+
_ => "nope",
228+
};
229+
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:
232+
```rust,ignore
233+
Some(v) if let Some(_) = take(v.clone()) => "ok",
234+
```
235+
> [!NOTE]
236+
> 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.
237+
> ```rust,ignore
238+
> use std::cell::Cell;
239+
>
240+
> let i: Cell<i32> = Cell::new(0);
241+
> match 1 {
242+
> 1 | _ if let Some(_) = { i.set(i.get() + 1); Some(1) } => {}
243+
> _ => {}
244+
> }
245+
> assert_eq!(i.get(), 1); // Guard not executed twice
246+
> ```
247+
153248
r[expr.match.attributes]
154249
## Attributes on match arms
155250

0 commit comments

Comments
 (0)