Const generics trait bounds

I'm trying to create a stack allocated array with a dimension specified by a recusive structure Dim<T, const N: usize>, where N is the number of elements at the current level.

By using specialization over a constant of trait ElemCount, I managed to count the number of elements. But when I was trying to implement some method for the array, the compiler always complains that the methods (or constants) are not found due to unsatisfied trait bounds.

Here is the link to code Rust Playground.

Why would the compiler complain about this? And how to cope with it?

I'm not sure, but I think it's a bug in specialization. There is a warning about it being incomplete and buggy, after all. There is also a problem that your impls depend on the value of <T as ElemCount>::N which cannot be normalized for arbitrary T. It may be that the build fails due to that, but the errors fail to pinpoint the real cause.

Anyway, your code is easy to fix if you use explicit impls of ElemCount for primitive types instead of overlapping impls and specialization, and also if you explicitly mention the required ElemCount trait bounds in your types (that may also be an issue in your original code, it's possible that the compiler can't use the blanket impl to derive impl ElemCount for a generic parameter, for whatever reason).


1 Like

Thanks for the help.