Skip to content

Commit a39ea16

Browse files
committed
Remove restriction on dereferencing pointers in const
We had said that the dereference operator could not be used with raw pointers in a constant expression. However, that restriction has been lifted. First, in Rust 1.58, we stabilized `const_raw_ptr_deref`. rust-lang/rust#89551 This allowed for dereferencing immutable raw pointers in a constant expression. Then, in Rust 1.83, we stabilized `const_mut_refs` and `const_refs_to_cell`. rust-lang/rust#129195 That allowed for: - Mentioning `&mut` types. - Creating `&mut` and `*mut` values. - Creating `&T` and `*const T` values where `T` contains interior mutability. - Dereferencing `&mut` and `*mut` values (both for reads and writes). Let's remove the stated restriction on dereferencing raw pointers in a constant expression and add examples.
1 parent 9753ddb commit a39ea16

File tree

1 file changed

+15
-1
lines changed

1 file changed

+15
-1
lines changed

src/const_eval.md

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -203,7 +203,21 @@ r[const-eval.const-expr.borrows]
203203
> See [issue #143129](https://github.com/rust-lang/rust/issues/143129) for more details.
204204
205205
r[const-eval.const-expr.deref]
206-
* The [dereference operator] except for raw pointers.
206+
* The [dereference operator].
207+
208+
```rust,no_run
209+
# use core::cell::UnsafeCell;
210+
const _: u8 = unsafe {
211+
let x = &raw mut *&mut 0; // Dereference of mutable reference.
212+
*x = 1; // Dereference of mutable pointer.
213+
*(x as *const u8) // Dereference of constant pointer.
214+
};
215+
const _: u8 = unsafe {
216+
let x = &UnsafeCell::new(0);
217+
*x.get() = 1; // Mutation of interior mutable value.
218+
*x.get()
219+
};
220+
```
207221
208222
r[const-eval.const-expr.group]
209223

0 commit comments

Comments
 (0)