What follows is just used as an example, and not valid Rust code.
struct Vec<T: Sized, Count> { a: [T; Count] }
Something like it is possible in C++ templates, but I haven't seen it in Rust.
To understand the reason, you first need to know two arrays are covariant and generics are invariant. Because of this fundamental reason, arrays and generics do not fit well with each other.
Quote: Arrays of generic types are not allowed because they're not sound. The problem is due to the interaction of Java arrays, which are not statically sound but are dynamically checked, with generics, which are statically sound and not dynamically checked.
Use the Reflection Class to Create Generic Arrays in Java In this type of approach, a reflection class is used to create a generic array whose type will be known at the runtime only. The only difference between the previous approach and this approach is that the reflection class is used as the constructor itself.
It is called generics.
Use const generics:
struct Vec<T: Sized, const COUNT: usize> { a: [T; COUNT], }
RFC 2000 — const generics introduces support for this and progress is tracked in issue #44580.
If you look at the design of Rust, you will notice that it started first by tackling the hardest problems (memory-safe, data-race free) but there are otherwise lots of areas where it is "incomplete" (compared to what could be achieved).
In particular, generic structures and functions started out somewhat limited:
For the moment, not all of these are implemented, not because they are not desired but simply because time was lacking. The idea of Rust 1.0 was not to release a final product that would not evolve, but a stable base from which to start; some or maybe all will come.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With