Skip to content

Commit 3d8c53d

Browse files
committed
Add examples
Thanks to RalfJ for the substance of many of these.
1 parent 62a33ad commit 3d8c53d

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

src/const_eval.md

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -85,11 +85,61 @@ r[const-eval.const-expr.borrows]
8585
mutable borrows and shared borrows to values with interior mutability
8686
are not allowed to refer to [lifetime-extended temporaries in the top-level scope of a `const` or `static` initializer expression][lifetime-extension-const].
8787

88+
```rust,compile_fail,E0492
89+
# use core::sync::atomic::AtomicU8;
90+
const C: &AtomicU8 = &AtomicU8::new(0); // ERROR not allowed
91+
```
92+
93+
```rust,compile_fail,E0492
94+
# use core::sync::atomic::AtomicU8;
95+
const C: &mut AtomicU8 = &mut AtomicU8::new(0); // ERROR not allowed
96+
```
97+
98+
```rust,compile_fail,E0492
99+
# use core::sync::atomic::AtomicU8;
100+
let _: &'static _ = const { &AtomicU8::new(0) }; // ERROR not allowed
101+
```
102+
103+
```rust
104+
# use core::sync::atomic::AtomicU8;
105+
const C: () = { _ = &AtomicU8::new(0); }; // OK
106+
```
107+
88108
In other words, they are only allowed to refer to *transient* places, to *indirect* places, or to *static* places.
89109
A place is *transient* if it is based on a local variable whose lifetime is strictly contained inside the current [const context].
110+
111+
```rust
112+
const C: () = {
113+
let mut x = 0;
114+
let _ = &mut x; // Reference to transient place.
115+
};
116+
```
117+
90118
A place is *indirect* if it is based on a [dereference expression][dereference operator].
119+
120+
```rust
121+
const C: () = {
122+
let mut x = 0;
123+
let x = &mut x;
124+
let _ = &mut *x; // Reference to an indirect place.
125+
};
126+
```
91127
A place is *static* if it is based on a `static` item or a [promoted expression].
92128

129+
```rust
130+
static mut S: u8 = 0;
131+
# #[allow(static_mut_refs)]
132+
const C: () = {
133+
let _ = unsafe { &mut S }; // Reference to a static place.
134+
};
135+
```
136+
137+
```rust
138+
const C: () = {
139+
let _: &'static mut [i32] = &mut []; // Reference to a promoted expression.
140+
};
141+
```
142+
93143
r[const-eval.const-expr.deref]
94144
* The [dereference operator] except for raw pointers.
95145

0 commit comments

Comments
 (0)