From 6f01103dbefe6287afc541ed176b1c69d3d6cdfe Mon Sep 17 00:00:00 2001 From: Remo Senekowitsch Date: Thu, 22 May 2025 20:51:25 +0200 Subject: [PATCH] Use inline const expression in unchecked-uninit.md Inline const expressions were stabilized in Rust 1.79. They allow us to avoid the unsafe call to MaybeUninit::assume_init() and its explanation. https://blog.rust-lang.org/2024/06/13/Rust-1.79.0/#inline-const-expressions --- src/unchecked-uninit.md | 18 +++--------------- 1 file changed, 3 insertions(+), 15 deletions(-) diff --git a/src/unchecked-uninit.md b/src/unchecked-uninit.md index 5665996..0f35fb9 100644 --- a/src/unchecked-uninit.md +++ b/src/unchecked-uninit.md @@ -23,12 +23,8 @@ use std::mem::{self, MaybeUninit}; const SIZE: usize = 10; let x = { - // Create an uninitialized array of `MaybeUninit`. The `assume_init` is - // safe because the type we are claiming to have initialized here is a - // bunch of `MaybeUninit`s, which do not require initialization. - let mut x: [MaybeUninit>; SIZE] = unsafe { - MaybeUninit::uninit().assume_init() - }; + // Create an uninitialized array of `MaybeUninit`. + let mut x = [const { MaybeUninit::uninit() }; SIZE]; // Dropping a `MaybeUninit` does nothing. Thus using raw pointer // assignment instead of `ptr::write` does not cause the old @@ -48,14 +44,7 @@ dbg!(x); This code proceeds in three steps: -1. Create an array of `MaybeUninit`. With current stable Rust, we have to use - unsafe code for this: we take some uninitialized piece of memory - (`MaybeUninit::uninit()`) and claim we have fully initialized it - ([`assume_init()`][assume_init]). This seems ridiculous, because we didn't! - The reason this is correct is that the array consists itself entirely of - `MaybeUninit`, which do not actually require initialization. For most other - types, doing `MaybeUninit::uninit().assume_init()` produces an invalid - instance of said type, so you got yourself some Undefined Behavior. +1. Create an array of `MaybeUninit`. 2. Initialize the array. The subtle aspect of this is that usually, when we use `=` to assign to a value that the Rust type checker considers to already be @@ -165,7 +154,6 @@ anywhere expects to be handed uninitialized memory, so if you're going to pass it around at all, be sure to be *really* careful. [`MaybeUninit`]: ../core/mem/union.MaybeUninit.html -[assume_init]: ../core/mem/union.MaybeUninit.html#method.assume_init [`ptr`]: ../core/ptr/index.html [raw_reference]: ../reference/types/pointer.html#r-type.pointer.raw.constructor [`write`]: ../core/ptr/fn.write.html