Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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_;
};

Thank you in advance!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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]
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading