Projecting from a MaybeUninit to a field

I would like to initialize a MaybeUninit a field at a time. Something like this:

    struct S(x, y);
    let mut s: MaybeUninit<S> = MaybeUninit::uninit();
    uninit_field_mut!(s, x).write(5);
    uninit_field_mut!(s, y).write(7);
    println!("{:?}", unsafe { s.assume_init() });

I did come up with an implementation that works, and it seems sound based on some code that I threw at it, but I am not 100% sure about it. Also I resorted to a slightly nasty trick in order to return a reference with the same lifetime as the input, and maybe there is a better way to do it.

Would anyone please review and perhaps suggest any improvements?

Link to playground

it's turned back into a reference to create a pointer to $field, but never really dereferenced.

I'd just avoid &mut altogether once you're in the land of *mut.

let target__ = unsafe { std::ptr::addr_of_mut!((*container__).$field) };

fn uninit_field_mut should be unsafe fn uninit_field_mut.

2 Likes

also, if you're working with unsafe code, run it through MIRI.

1 Like

Oh yeah, good advice - it does pass miri.

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.