Can a Rust struct be parametrized with values instead of types?

Viewed 70

I'm learning Rust and it is not clear to me if it is possible to have a Rust struct parametrized with some values (as well as types). In order to be more clear, is it possible in Rust to build a struct that mimic the behaviour of this C++ struct?

template <int dim, class T>
struct Data
{
  std::array<T, dim> data_;
};
1 Answers

Certainly, you need a const generic parameter.

struct Data<T, const N: usize> {
    member: [T; N],
}

fn main() {
    let d = Data { member: [0; 6] };
    println!("{:?}", d.member); // [0, 0, 0, 0, 0, 0]
}
Related