How to create array field with the size of another field

I want to be able to determine the size of my array field with another field, so something like:

struct ExStruct {
    size_of_array: i32,
    array: [i32; size_of_array],
}

thanks in advance for any help

The size of arrays are a part of their type, so it has to be known at compile time and can't change at runtime (without also changing the type, e.g. copying to a different one). If you have a fixed set of known lengths to support, arrays with const generics may be an option; however, each ExStruct with a distinct array length field will be a distinct type, which may be too limiting for you.

struct ExStruct<const LEN: usize> {
    array: [i32; LEN],
}

const generics is still a developing area of Rust, and there's only so much you can do on stable with regards to generically relating types with different lengths and so on.


You may be better off with a Vec or SmallVec or some other dynamically sized abstraction.

You could use const generics:

struct ExStruct<const N: usize> {
    array: [i32; N],
    size_of_array: N,
}

Edit: quinedot beat me to it