-
Notifications
You must be signed in to change notification settings - Fork 532
if let
guards documentation
#1823
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Kivooeo
wants to merge
1
commit into
rust-lang:master
Choose a base branch
from
Kivooeo:master
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+98
−3
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change | ||||
---|---|---|---|---|---|---|
|
@@ -9,15 +9,19 @@ MatchExpression -> | |||||
MatchArms? | ||||||
`}` | ||||||
|
||||||
Scrutinee -> Expression _except [StructExpression]_ | ||||||
Scrutinee -> | ||||||
Expression _except_ [StructExpression] | ||||||
|
||||||
MatchArms -> | ||||||
( MatchArm `=>` ( ExpressionWithoutBlock `,` | ExpressionWithBlock `,`? ) )* | ||||||
MatchArm `=>` Expression `,`? | ||||||
|
||||||
MatchArm -> OuterAttribute* Pattern MatchArmGuard? | ||||||
MatchArm -> | ||||||
OuterAttribute* Pattern MatchArmGuard? | ||||||
|
||||||
MatchArmGuard -> `if` Expression | ||||||
MatchArmGuard -> | ||||||
`if` Expression | ||||||
| `if` Expression `&&` LetChain | ||||||
``` | ||||||
<!-- TODO: The exception above isn't accurate, see https://github.com/rust-lang/reference/issues/569 --> | ||||||
|
||||||
|
@@ -150,6 +154,97 @@ This allows shared borrows to be used inside guards without moving out of the sc | |||||
r[expr.match.guard.no-mutation] | ||||||
Moreover, by holding a shared reference while evaluating the guard, mutation inside guards is also prevented. | ||||||
|
||||||
r[expr.match.if.let.guard] | ||||||
## If Let Guards | ||||||
Match arms can include `if let` guards to allow conditional pattern matching within the guard clause. | ||||||
|
||||||
r[expr.match.if.let.guard.syntax] | ||||||
```rust,ignore | ||||||
match expression { | ||||||
pattern if let subpattern = guard_expr => arm_body, | ||||||
... | ||||||
} | ||||||
``` | ||||||
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. | ||||||
|
||||||
r[expr.match.if.let.guard.behavior] | ||||||
When the pattern matches successfully, the `if let` expression in the guard is evaluated: | ||||||
* The guard proceeds if the inner pattern (`subpattern`) matches the result of `guard_expr`. | ||||||
* Otherwise, the next arm is tested. | ||||||
|
||||||
```rust,ignore | ||||||
let value = Some(10); | ||||||
|
||||||
let msg = match value { | ||||||
Some(x) if let Some(y) = Some(x - 1) => format!("Matched inner value: {}", y), | ||||||
_ => "No match".to_string(), | ||||||
}; | ||||||
``` | ||||||
|
||||||
r[expr.match.if.let.guard.scope] | ||||||
* The `if let` guard may refer to variables bound by the outer match pattern. | ||||||
* 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. | ||||||
|
||||||
```rust,ignore | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||
let opt = Some(42); | ||||||
|
||||||
match opt { | ||||||
Some(x) if let Some(y) = Some(x + 1) => { | ||||||
// Both `x` and `y` are available in this arm, | ||||||
// since the pattern matched and the guard evaluated to true. | ||||||
println!("x = {}, y = {}", x, y); | ||||||
} | ||||||
_ => { | ||||||
// `y` is not available here --- it was only bound inside the guard above. | ||||||
// Uncommenting the line below will cause a compile-time error: | ||||||
// println!("{}", y); // error: cannot find value `y` in this scope | ||||||
} | ||||||
} | ||||||
|
||||||
// Outside the match expression, neither `x` nor `y` are in scope. | ||||||
``` | ||||||
|
||||||
* The outer pattern variables (`x`) follow the same borrowing behavior as in standard match guards (see below). | ||||||
|
||||||
r[expr.match.if.let.guard.borrowing] | ||||||
Before a guard (including an `if let` guard) is evaluated: | ||||||
1. Pattern bindings are performed first | ||||||
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. | ||||||
```rust,ignore | ||||||
match Some(String::from("hello")) { | ||||||
Some(s) if /* guard */ => { /* s is moved here */ } | ||||||
_ => {} | ||||||
} | ||||||
``` | ||||||
2. Guard evaluation happens after that, and: | ||||||
* Guard evaluation follows successful main pattern match. Variables bound by the main pattern are usable within the guard, respecting their binding type (borrow/move) | ||||||
* Moves from the scrutinee in the guard are subject to standard Rust ownership rules. Avoid moving what's needed later; already moved parts from the main pattern can be used. | ||||||
* Variables successfully bound within the if let guard are in scope within the corresponding match arm body. Their scope extends to the arm after the guard condition is met. | ||||||
```rust,ignore | ||||||
let val = Some(vec![1, 2, 3]); | ||||||
|
||||||
let result = match val { | ||||||
Some(v) if let Some(_) = take(v) => "ok", // ERROR: cannot move out of `v` | ||||||
_ => "nope", | ||||||
}; | ||||||
``` | ||||||
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: | ||||||
```rust,ignore | ||||||
Some(v) if let Some(_) = take(v.clone()) => "ok", | ||||||
``` | ||||||
> [!NOTE] | ||||||
> Multiple matches using the `|` operator can cause the pattern guard and the side effects it has to execute multiple times. For example: | ||||||
> ```rust,ignore | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||
> use std::cell::Cell; | ||||||
> | ||||||
> let i: Cell<i32> = Cell::new(0); | ||||||
> match 1 { | ||||||
> 1 | _ if let Some(_) = { i.set(i.get() + 1); Some(1) } => {} | ||||||
> _ => {} | ||||||
> } | ||||||
> assert_eq!(i.get(), 2); // Guard is executed twice | ||||||
> ``` | ||||||
|
||||||
r[expr.match.attributes] | ||||||
## Attributes on match arms | ||||||
|
||||||
|
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Would it be possible to make a working example?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Im not really sure, because it's not stable feature and contains behind
#![feature...]
gate that's aren't allowed in documentation and CI will fail with this error