What's a good way to fill in a vector of structs in Rust where:
- The size is dynamic, but known at the time of initialization.
- Doesn't first initialize the memory to a dummy value.
- Doesn't re-allocate memory as its filled.
- In this example, all members of the vector are always initialized.
(In keeping with Rusts assurance of no undefined behavior).
And ideally
- Doesn't index check each index access
(since the size is known when declaring the vector this should be possible). - Doesn't require
unsafe
(Not sure if this is reasonable, however the compiler _could_ detect that all values are always filled, allowing such logic in an unsafe block).
The C equivalent is:
struct MyStruct *create_mystruct(const uint n) {
struct MyStruct *vector = malloc(sizeof(*vector) * n);
for (uint i = 0; i < n; i++) {
/* any kind of initialization */
initialize_mystruct(&vector[i], i);
}
return vector;
}
I'm porting over some C code which fills an array in a simple loop, so I was wondering if there was a Rustic way to perform such a common task with zero or at least minimal overhead?
If there are typically some extra checks needed for the Rust version of this code, what's the nearest equivalent?