How to make a type depend on a constant generic parameter in Rust?

4 weeks ago 28
ARTICLE AD BOX

I am very new to Rust. I want to have a type depend on a constant generic parameter in Rust. In C++, this can easily be achieved with some metaprogramming:

template<std::size_t N> struct MyStruct { using MyType = char const *; }; template<> struct MyStruct<0> { using MyType = std::int8_t; }; template<> struct MyStruct<1> { using MyType = std::int16_t; };

I tried doing something similar in Rust:

trait MyTrait { type MyType; } struct MyStruct<const N: usize>; impl<const N: usize> MyTrait for MyStruct<N> { type MyType = str; } impl MyTrait for MyStruct<0> { type MyType = i8; } impl MyTrait for MyStruct<1> { type MyType = i16; }

This doesn't work. The compiler says:

... conflicting implementations of trait `MyTrait` for type `MyStruct<0>` ... conflicting implementations of trait `MyTrait` for type `MyStruct<1>` ...

I would have expected Rust to understand that the first generic implementation for MyStruct<N> is only the default case when it couldn't math any other, like it is the case in C++. I did some research and it seems that there is a way to make it work by explicitly restricting the values of N for which the first generic implementation is defined, but that requires enabling an experimental feature from a nightly build of the compiler. However, I'm looking for a way to do it with the latest stable compiler release, without any experimental features enabled. Is there a way to do so or is Rust inherently limited in metaprogramming compared to C++?

Read Entire Article