Does uninitialized memory count as an "initialized" MaybeUninit?

For example, the docs for Vec::set_len() say that "The elements at old_len..new_len must be initialized". Would the following be sound?

use std::mem::MaybeUninit;

fn main() {
    let mut a: Vec<MaybeUninit<u8>> = Vec::with_capacity(10);

    unsafe {

    // do whatever with `a[0..10]`, respecting MaybeUninit's API contracts

The Vec's elements definitely haven't been explicitly initialized (through e.g. MaybeUninit::uninit()). So is a MaybeUninit reinterpreted from uninitialized memory considered "initialized" for the purpose of Vec::set_len() and similar guarantees? The docs aren't really clear about this.

Yes, this is definitely sound.

My intuition says the same thing, but can you offer anything to back that claim up? I'm finding it difficult to actually get a guarantee for this from the docs or the nomicon.

You can check the general docs of

otherwise this would be a combination of:

  1. Vec::spare_capacity…

    which would give you a &mut [MaybeUninit<Elem> /*; 10 or more */], with Elem being MaybeUninit<T>, thence yielding nested MaybeUninit.

  2. MaybeUninits can be flattened, as array constructor examples showcase.

That is, the following could be the quote you are looking for:

1 Like

“must be initialized” is code word for “must uphold the initialization invariant”, and the docs of MaybeUninit state that “a signal to the compiler indicating that the data here might not be initialized” which is code word for “removes the initialization invariant” — therefore, MaybeUninit is always considered initialized in terms of the type itself. It’s not the most rigorous proof I will admit, but Yandros’ example can supplement it.

Yeah, those explanations are convincing enough for me, thanks for the references :slight_smile: I'll try to think of a good paragraph to add to the MaybeUninit docs about this.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.