Allocate a boxed array of MaybeUninit

The answer for how you make a boxed slice is essentially always to go through Vec. (Or .collect(), which uses Vec internally.)

So you might want to just go for something simple like

fn make_uninit<T>(n: usize) -> Box<[MaybeUninit<T>]> {
    std::iter::repeat_with(MaybeUninit::uninit)
        .take(n)
        .collect()
}

Which looks like it optimizes plenty well enough: https://rust.godbolt.org/z/85sGnc75v

9 Likes