This is hard and, to some extent, anti-idiomatic, because Rust will try to prevent you manipulating uninitialized memory by any means. And, even though it sounds like a limitation if you come from C++, you have to realize that everything does not translate literally from C++ to Rust, even though the two languages share a lot.
For instance, if you:
- don't want to fill a vector with default values,
- don't want
push
values while going on,
then you may be better off building an iterable, and collect
ing it.
You could also fill the vector with None
s.
In particular, Rust incentivizes you not to leave the possibility of a variable pointing to uninitialized memory. That is, even if you achieve (as I will explain later) to have uninitialized memory, Rust will require you to work with unsafe
blocks when you access it, until you have "certified" it's all initialized, and even then you are never allowed to read from uninitialized memory, which results in UB (which is the worst could happen).
If you really want to work with uninitialized memory, then read the relevant chapter of the rustnomicon. In the end, what you will use is MaybeUninit. However, read carefully the rustnomicon too (not only the doc page of MaybeUninit), as it contains subtleties.