Can i define a trait implementing another trait’s associated function when there is already a generic implementation for the trait Im implementing?

Viewed 87

Context: I am working with an external crate that defines a trait ExternalTrait eg

pub trait ExternalTrait {
    fn associated_func() -> i32;
}

I have several types that have almost identical implementations of said trait, differing only by a single value, so I want to defined my own trait implementing the external one where the only required definition is the value that differs.

e.g.

trait MyImplementation {
    fn custom_value() -> i32;
}

One way i attempted to do this that does not work is

impl ExternalTrait for dyn MyImplementation {
    fn associated_func() -> i32 {
        &Self::custom_value()
    }
}

which fails because MyImplementation, having an associated function, is not object safe.

What does work is

impl<T> ExternalTrait for T
where
    T: MyImplementation,
{
    fn associated_func() -> i32 {
        T::custom_value()
    }
}

which is great, except that the external crate I'm working with already has a generic implementation for that trait, like this:

impl<'a, Y> ExternalTrait for &'a Y
where
    Y: ?Sized,
    Y: ExternalTrait,
{
    fn associated_func() -> i32 {
        10
    }
}

which understandably conflicts with the one I'm defining. So the question is, is there a way to support my use-case, aside from using macros?

Cheers

e: additional context. The above was just me trying to come up with a minimal example. The actual external trait that I'm running into this in practice is https://docs.rs/juniper/0.15.1/juniper/trait.GraphQLType.html and conflicting implementation is https://docs.rs/juniper/0.15.1/juniper/trait.GraphQLType.html#impl-GraphQLType%3CS%3E-for-%26%27e%20T. It is possible to implement it for a concrete struct just fine, e.g.

impl GraphQLType<DefaultScalarValue> for MyStruct

0 Answers
Related