Skip to content

Commit 7d0932d

Browse files
committed
Clarify note about extended temps in initializers
We have a note that describes why, perhaps surprisingly, it's OK to have a reference to a static with an interior mutable value in the final value of a constant item but it's not OK if the interior mutable value is a temporary from the initializer. There was room to improve how this was worded, so let's take it.
1 parent 2501b16 commit 7d0932d

File tree

1 file changed

+10
-2
lines changed

1 file changed

+10
-2
lines changed

src/items/constant-items.md

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -142,14 +142,22 @@ const _: &&mut u8 = unsafe { &S }; // OK.
142142
> This is allowed as it's separately not allowed to read from an external static during constant evaluation. See [const-eval.const-expr.path-static].
143143
144144
> [!NOTE]
145-
> We also disallow, in the final value, shared references to mutable statics created in the initializer for a separate reason. Consider:
145+
> As described above, we accept, in the final value of constant items, shared references to static items whose values have interior mutability.
146+
>
147+
> ```rust
148+
> # use core::sync::atomic::AtomicU8;
149+
> static S: AtomicU8 = AtomicU8::new(0);
150+
> const _: &AtomicU8 = &S; // OK.
151+
> ```
152+
>
153+
> However, we disallow similar code when the interior mutable value is created in the initializer.
146154
>
147155
> ```rust,compile_fail,E0492
148156
> # use core::sync::atomic::AtomicU8;
149157
> const _: &AtomicU8 = &AtomicU8::new(0); // ERROR.
150158
> ```
151159
>
152-
> Here, the `AtomicU8` is a temporary that is lifetime extended to `'static` (see [destructors.scope.lifetime-extension.static]), and references to lifetime-extended temporaries with interior mutability are not allowed in the final value of a constant expression (see [const-eval.const-expr.borrows]).
160+
> Here, the `AtomicU8` is a temporary whose scope is extended to the end of the program (see [destructors.scope.lifetime-extension.static]). Such temporaries with interior mutability cannot be borrowed in constant expressions (see [const-eval.const-expr.borrows]).
153161
154162
r[items.const.expr-omission]
155163
The constant expression may only be omitted in a [trait definition].

0 commit comments

Comments
 (0)