Using generic trait bound in struct generic over said bound


So basically I’d like to do something like:

pub struct Matrix<T,A:MatCollection<T>, D:  Dim + ?Sized>{
    pub data: A,    
    pub dim: D,    

Where MatCollection is a marker trait for collections and T is supposed to be the type of said collection’s contents. I want to be able to be generic over all types T, yet I don’t actually use type T in my struct, so I get the error: error[E0392]: parameter T is never used.

However, I do need type T to be able to return contents from A in the implementation of the struct.

I’m probably going about this all wrong, but I can’t seem to figure out the right way to do this. I’ve been looking at other matrix implementations in rust and they all have clever solutions, like wrapping the collections in a new type, yet this seems like the most natural way to design this for me.


Here are two ideas:

  • Instead of having a generic trait MatCollection<T>, make it a non-generic trait MatCollection with an associated type T. This prevents a type from implementing MatCollection multiple times for different types T, but do you expect that to happen?
  • If you must have a generic trait, then add a PhantomData<T> member to the Matrix struct in order to trick the type system into thinking that T is used.


Thank you!

Both of those approaches do fix the problem I mentioned. The compiler did mention using PhantomData but it took me a while to realize how it was meant to be used. For now it works, but associated types might indeed make a bit more sense in this context.