Skip to content

Commit 56fe773

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 56fe773

File tree

1 file changed

+17
-1
lines changed

1 file changed

+17
-1
lines changed

src/const_eval.md

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -203,7 +203,23 @@ 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: *mut u8 = &raw mut *&mut 0;
212+
// ^^^^^^^
213+
// Dereference of mutable reference.
214+
*x = 1; // Dereference of mutable pointer.
215+
*(x as *const u8) // Dereference of constant pointer.
216+
};
217+
const _: u8 = unsafe {
218+
let x = &UnsafeCell::new(0);
219+
*x.get() = 1; // Mutation of interior mutable value.
220+
*x.get()
221+
};
222+
```
207223
208224
r[const-eval.const-expr.group]
209225

0 commit comments

Comments
 (0)