How to handle conflicting implementations of trait

Hi!

I can't wrap my head around why the following code throws "Conflicting implementations of trait" error:

pub struct A;

pub trait Trait<T> {
    fn do_something(input: T);
}

impl<T> Trait<T> for A
where
    T: Add<T>,
{
    fn do_something(input: T) {}
}

// Conflicting implementations of trait 
impl<T> Trait<T> for A
where
    T: Add<T> + Mul<T>,
{
    fn do_something(input: T) {}
}

I would like to handle the two implementations differently, but I'm not sure how to go about it.

Any help would be appreciated :slight_smile:

This would require specialization which is an unstable feature.

Thanks @bjorn3 ! Is there any workaround for this?

It doesn't work in generic contexts though. Only if the concrete type is known. Otherwise it will fallback to the most general implementation.

Hm interesting, thanks for sharing! For now I'll just have to duplicate for each concrete type, since I don't have many.

But I would be curious to learn why this specific case is considered "conflicting impl". How could Add and Add + Mul be conflicting, since one is strictly more specific than the other??

For types implementing both Add and Mul both implementations apply and thus conflict with eachother. The whole point of specialization is to allow such conflicts if one implementation applies in a strict subset of another marked as specializable.

1 Like