Skip to content

Commit 52c6561

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 52c6561

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed

src/expressions/match-expr.md

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -147,6 +147,26 @@ 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, the scrutinee may undergo [constant promotion], even if later moved.
152+
>
153+
> ```rust
154+
> struct S;
155+
> let _y: &'static S;
156+
> match S {
157+
> // ^ 1. The scrutinee is evaluated into a temporary place and
158+
> // a shared borrow is taken, causing promotion.
159+
> //
160+
> x if { _y = &x; true } => {}
161+
> // ^ ^^^^^^^ 2. This references the promoted value.
162+
> // |
163+
> // 3. The move into `x` happens after the value has been promoted.
164+
> _ => (),
165+
> }
166+
> ```
167+
>
168+
> See [issue #145237](https://github.com/rust-lang/rust/issues/145237) for more details.
169+
150170
r[expr.match.guard.no-mutation]
151171
Moreover, by holding a shared reference while evaluating the guard, mutation inside guards is also prevented.
152172
@@ -163,6 +183,7 @@ r[expr.match.attributes.inner]
163183
[`cfg`]: ../conditional-compilation.md
164184
[attributes on block expressions]: block-expr.md#attributes-on-block-expressions
165185
[binding mode]: ../patterns.md#binding-modes
186+
[constant promotion]: destructors.scope.const-promotion
166187
[Inner attributes]: ../attributes.md
167188
[lint check attributes]: ../attributes/diagnostics.md#lint-check-attributes
168189
[pattern]: ../patterns.md

0 commit comments

Comments
 (0)