Generic Trait Implementation

Hi everyone. I'm trying to implement a trait, for example Display, over a generic type that implements a generic trait without having to repeat the impl block for each implemented types:

trait Tuple<P> { ... }

struct Vector3<P> { ... }
struct Point3<P> { ... }

impl<P> Tuple<P> for Vector3<P> { ... }
impl<P> Tuple<P> for Point3<P> { ... }

// This works:
impl<P> Display for Vector3<P> where P: Display { ... }
impl<P> Display for Point3<P> where P: Display { ... }

Is it possible to make it work with just one generic implementation, similar to this?

impl<T, P> Display for T where T: Tuple<P> { ... }

When I tried, I get the error:
[E0207]: the type parameter P is not constrained....

I tried to bound the parameter as an associated type, but still get the same error:

trait Tuple<P> { 
    type Primitive;

impl<T, P> Display for T where T: Tuple<P, Primitive = P> { ... } 

And also tried using an associated type default:

trait Tuple<P> { 
    type Primitive = P;

But unfortunately I also get the error:
[E0658]: associated type defaults are unstable.

I am not sure if having a single impl block for the generic type is even possible, or if it requires associated type defaults to be stable or even if specialization is required...

Any guidance is greatly appreciated. Thanks.

If a type implements both Tuple<u32> and Tuple<f64>, which of these implementations should Display use?

1 Like

You can't use blanket implementions for foreign traits, per E210. Your only option would be to create a wrapper struct, something like this: Rust Playground


Thank you very much for the guidance.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.