Skip to content

Commit 924e588

Browse files
committed
Add clarifications
In the text as revised, it wasn't clear what rule prevented a mutable reference from appearing in the final value of a constant item, so let's add a rule specifically for that. Similarly, it may not be immediately clear what rule prevents a reference to a lifetime-extended interior mutable temporary created in the initializer, so let's add an admonition section describing how other rules apply to prevent this.
1 parent 24a4f32 commit 924e588

File tree

1 file changed

+18
-0
lines changed

1 file changed

+18
-0
lines changed

src/items/constant-items.md

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,24 @@ const BITS_N_STRINGS: BitsNStrings<'static> = BitsNStrings {
4848
};
4949
```
5050

51+
r[items.const.final-value-immutable]
52+
The final value of a `const` item cannot contain a mutable reference.
53+
54+
```rust
55+
static S: u8 = 0;
56+
const C1: &u8 = &mut S; // OK
57+
const C2: &mut u8 = &mut S; // ERROR not allowed
58+
```
59+
60+
> [!NOTE]
61+
> We also disallow, in the final value, shared references to mutable statics created in the initializer for a separate reason. Consider:
62+
>
63+
> ```rust
64+
> const C: &AtomicU8 = &AtomicU8:new(0); // ERROR
65+
> ```
66+
>
67+
> 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]).
68+
5169
r[items.const.expr-omission]
5270
The constant expression may only be omitted in a [trait definition].
5371

0 commit comments

Comments
 (0)