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

How is it possible to take an array with any size as a generic type in rust?

I would like to have a generic struct, that has an array of MyType in it. It can be any size but can not be changed, that is why I want to use generic.

I tried it like this:

pub struct MyStruct<[MyType, COUNT]> {
    data: [MyType, COUNT],
}

I get syntax error expected COMMA without any useful guides from the compiler.

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 :

The correct syntax is

pub struct MyStruct<MyType, const COUNT: usize> {
    data: [MyType; COUNT],
}

The parameter COUNT needs to be annotated as a constant. There are no square brackets around the type parameters. The delimiter between the type and the count in an array type is a semicolon, not a comma.

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