Skip to content

Initializing struct fields with MaybeUninit #62965

Closed
@Osspial

Description

@Osspial

The MaybeUninit docs have one weird, concerning section:

There is currently no supported way to create a raw pointer or reference to a field of a struct inside MaybeUninit<Struct>. That means it is not possible to create a struct by calling MaybeUninit::uninit::<Struct>() and then writing to its fields.

However, there seems to be a pretty clear, simple way to do that:

use std::mem::MaybeUninit;

fn main() {
    struct Foo {a: u32, b: bool}
    let mut idk: MaybeUninit<Foo> = MaybeUninit::uninit();
    unsafe{ (*idk.as_mut_ptr()).b = true; }
}

If you run that through MIRI, it doesn't complain, which strongly implies that the documentation is incorrect: https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=1862e046da3dbd485f83fd8ffa1ce4fd

So, is the documentation incorrect, or is MIRI incorrectly accepting the above code as defined behavior?

(It's worth noting that MIRI correctly rejects using mem::uninitialized() in that context: https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=02e33fd2582dcaeaf2b97e9e0db7e0d1)

cc #53491 @RalfJung

Metadata

Metadata

Assignees

No one assigned

    Labels

    C-feature-requestCategory: A feature request, i.e: not implemented / a PR.F-raw_ref_op`#![feature(raw_ref_op)]`T-langRelevant to the language team

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions