Allocate multiple instances of a struct in one continuous block

I have recently decided to learn Rust and thus read the book and tried to rewrite one of my C projects in Rust. There, I need to read a file and create multiple instances of a struct, let say something like
struct Data { id: u64, values: Vec<i32> }
The program will need to access these values very frequently, thus I would like to have them in one continuous memory block to maybe profit of some caching. In C I would just malloc a block of the size of the struct multiplied with the number of instances I need, but how would I do this in rust? I tried something like
let values = vec![Data::new(); num_values];
with some simply default construct named new, but would this actually result in one continuous memory block?

Thank you!

Yes, Vec is a single contiguous memory block.

From the docs

A contiguous growable array type, written Vec<T> but pronounced 'vector'.


Note, however, that your values field is also a Vec, which will put all of its contents in a separate allocation from the parent structure. If every Data instance needs the same number of values, consider using an array there instead. This will keep them inside the struct itself:

struct Data { id: u64, values: [i32;16] }

I am not sure if this is related. But these are also interesting to use for allocating a chunk of memory.



1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.