Skip to content

Commit a350402

Browse files
committed
Document promotion of match scrutinees due to guards
Borrowing part of a match scrutinee from within the guard can trigger constant promotion even if that part of the scrutinee is later moved into a variable. Let's add a note about this.
1 parent 6110395 commit a350402

File tree

1 file changed

+18
-0
lines changed

1 file changed

+18
-0
lines changed

src/expressions/match-expr.md

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -147,6 +147,23 @@ r[expr.match.guard.value]
147147
Only when the guard evaluates to true is the value moved, or copied, from the scrutinee into the variable.
148148
This allows shared borrows to be used inside guards without moving out of the scrutinee in case guard fails to match.
149149
150+
> [!NOTE]
151+
> Due to this, borrowing within the guard can cause [constant promotion] of the part of the scrutinee borrowed, even if that part is later moved into a variable.
152+
>
153+
> ```rust
154+
> struct S;
155+
> let _y: &'static S;
156+
> match S {
157+
> x if { _y = &x; true } => {}
158+
> // ^ ^^^^^^^ 1. This happens first, before the move into `x`.
159+
> // |
160+
> // 2. The move into `x` happens second, after `x` has been promoted.
161+
> _ => (),
162+
> }
163+
> ```
164+
>
165+
> See [issue #145237](https://github.com/rust-lang/rust/issues/145237) for more details.
166+
150167
r[expr.match.guard.no-mutation]
151168
Moreover, by holding a shared reference while evaluating the guard, mutation inside guards is also prevented.
152169
@@ -163,6 +180,7 @@ r[expr.match.attributes.inner]
163180
[`cfg`]: ../conditional-compilation.md
164181
[attributes on block expressions]: block-expr.md#attributes-on-block-expressions
165182
[binding mode]: ../patterns.md#binding-modes
183+
[constant promotion]: destructors.scope.const-promotion
166184
[Inner attributes]: ../attributes.md
167185
[lint check attributes]: ../attributes/diagnostics.md#lint-check-attributes
168186
[pattern]: ../patterns.md

0 commit comments

Comments
 (0)