Skip to content

Commit 4f70560

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 4f70560

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

src/items/constant-items.md

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

51+
r[items.const.no-mutable-ref]
52+
The final value of a `const` item cannot contain a mutable reference.
53+
54+
```rust
55+
# use core::sync::atomic::AtomicU8;
56+
static mut S_M: u8 = 0;
57+
static S_IM: AtomicU8 = AtomicU8::new(0);
58+
const C_M: &u8 = unsafe { &mut S_M }; // OK
59+
const C_IM: &AtomicU8 = &S_IM; // OK
60+
```
61+
62+
```rust,compile_fail,E0080
63+
# static mut S_M: u8 = 0;
64+
const C_MR: &mut u8 = unsafe { &mut S_M }; // ERROR not allowed
65+
```
66+
67+
> [!NOTE]
68+
> We also disallow, in the final value, shared references to mutable statics created in the initializer for a separate reason. Consider:
69+
>
70+
> ```rust,compile_fail,E0492
71+
> # use core::sync::atomic::AtomicU8;
72+
> const C: &AtomicU8 = &AtomicU8::new(0); // ERROR
73+
> ```
74+
>
75+
> 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]).
76+
5177
r[items.const.expr-omission]
5278
The constant expression may only be omitted in a [trait definition].
5379

0 commit comments

Comments
 (0)