Skip to content

Commit dd6e807

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 dd6e807

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

src/items/constant-items.md

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

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

0 commit comments

Comments
 (0)