ideasman42
ideasman42

Reputation: 48248

How to perform efficient vector initialization in Rust?

What's a good way to fill in a vector of structs in Rust where:

And ideally

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?

Upvotes: 5

Views: 6576

Answers (1)

Shepmaster
Shepmaster

Reputation: 432119

Just use map and collect.

struct MyStruct(usize);

fn create_mystructs(n: usize) -> Vec<MyStruct> {
    (0..n).map(MyStruct).collect()
}

"Initializing" doesn't make sense in safe Rust because you'd need to have the ability to access the uninitialized values, which is unsafe. The Iterator::size_hint method can be used when collecting into a container to ensure that a minimum number of allocations is made.

Basically, I'd trust that the optimizer will do the right thing here. If it doesn't, I'd believe that it eventually will.

Upvotes: 11

Related Questions