Why use `ptr::write` with arrays of `MaybeUninit`s?

前端 未结 1 815
暗喜
暗喜 2021-02-14 03:35

In the standard library, the documentation shows how to instantiate arrays of MaybeUninits:

let arr: [MaybeUninit; N] =
    MaybeUninit::un         


        
1条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-14 03:58

    let arr: [MaybeUninit; N] = MaybeUninit::uninit().assume_init(); is just a shortcut.

    arr[i] = MaybeUninit::new(value), in your example arr[i] is a MaybeUninit so your question is just about what style to use to mutate a vector. You could also do arr[i].write(value) that doesn't really change in practice but it's require nightly that why the doc don't use it. But you are right arr[i] = MaybeUninit::new(value) allow to override the value too without unsafe keyword and it's a perfectly defined behavior.

    The thing you forget is that MaybeUninit is not really here to be used only inside Rust except very few case, Rust don't need it. We mostly use it when we dealing with ffi, so the exemple is not really a real word use case. So it can look strange. Here the author probably want to emulate a real word case where the array would be init outside Rust by using a raw pointer.

    0 讨论(0)
提交回复
热议问题