Define array size at compile time

I would like to do something like this

Struct ParameterizedArray<n:usize> {
first:[u8; n],
second: [u64,2*n],
}

which doesn't work as usize is not a trait. Any way to handle this properly?

Yes, using the unstable / in-the-works const_generics feature:

#![feature(const_generics)]

struct ParameterizedArray<const N: usize> {
    first: [u8; N],
    second: [u64; 2 * N], /* Not yet supported, though */
}

That being said, that feature still has many rough edges, and won't be stabilized soon. The one that is very likely to be stabilized soon is a subset of that feature, called min_const_generics. It allows having stuff such as [u8; N] depending on a const N: usize generic parameter, but does not allow non-trivial expressions, such as your 2 * N:

#![feature(min_const_generics)]

struct ParameterizedArray<const N: usize> {
    first: [u8; N],
    // second: [u64; 2 * N], /* Would error */
}
2 Likes

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.