Skip to content

Commit 0955af2

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

File tree

1 file changed

+70
-0
lines changed

1 file changed

+70
-0
lines changed

src/const_eval.md

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -85,11 +85,81 @@ 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,E0764
94+
# use core::sync::atomic::AtomicU8;
95+
const C: &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+
108+
```rust
109+
# use core::sync::atomic::AtomicU8;
110+
static S: AtomicU8 = AtomicU8::new(0);
111+
const C: &AtomicU8 = &S; // OK
112+
```
113+
88114
In other words, they are only allowed to refer to *transient* places, to *indirect* places, or to *static* places.
89115
A place is *transient* if it is based on a local variable whose lifetime is strictly contained inside the current [const context].
116+
117+
```rust
118+
const C: () = {
119+
let mut x = 0;
120+
let _ = &mut x; // Reference to a transient place.
121+
};
122+
```
123+
90124
A place is *indirect* if it is based on a [dereference expression][dereference operator].
125+
126+
```rust
127+
const C: () = {
128+
let x = &mut 0;
129+
let _ = &mut *x; // Reference to an indirect place.
130+
};
131+
```
132+
91133
A place is *static* if it is based on a `static` item or a [promoted expression].
92134

135+
```rust
136+
static mut S: u8 = 0;
137+
# #[allow(static_mut_refs)]
138+
const C: &u8 = unsafe { &mut S }; // Borrow of static item.
139+
```
140+
141+
```rust
142+
static mut S: u8 = 0;
143+
# #[allow(static_mut_refs)]
144+
const C: () = {
145+
let _ = unsafe { &mut S }; // Borrow of static item.
146+
};
147+
```
148+
149+
```rust
150+
const C: &[u8] = &mut []; // Borrow of promoted expression.
151+
```
152+
153+
```rust
154+
const C: &[u8] = &[]; // Borrow of promoted expression.
155+
```
156+
157+
```rust
158+
const C: () = {
159+
let _: &'static mut [u8] = &mut []; // Borrow of promoted expression.
160+
};
161+
```
162+
93163
r[const-eval.const-expr.deref]
94164
* The [dereference operator] except for raw pointers.
95165

0 commit comments

Comments
 (0)