Conflicting implementations Error

Hi there, I am having some difficult in trying to implement a trait for a struct which has generics, but having slightly different code for the same method name. Below is an example of what I am trying to achieve

trait MyTrait {
    fn my_check(&self) -> bool;
}

trait MyOtherTrait {
    fn my_other_check(&self) -> bool;
}

struct Problem<C> {
    data: C,
}

trait SetData {
    fn set_data(&mut self);
}

impl<C: MyTrait> SetData for Problem<C> {
    fn set_data(&mut self) {
        // do something
    }
}

impl<C: MyTrait + MyOtherTrait> SetData for Problem<C> {
    fn set_data(&mut self) {
        // do something else
    }
}

Problem is my struct with a generic C and I want to implement the SetData trait, but do so slightly differently for when the generic C has the trait MyTrait and for when it has MyTrait and MyOtherTrait.

Any help on how to navigate around this problem would be much appreciated.

Thanks
Karl

This is called specialization and it's not currently possible: if you think about it, the second impl includes the first one, so which one should apply to a type that satisfies both?

You will have to re-define the problem. What is the higher-level problem you are trying to solve? There might be a completely different, easier solution.

Thanks for the response.

It makes sense about what you said about which one should apply; I wasnt sure if internally it would only invoke the one with two traits if they were both present.

I have some other code that will take the struct problem and call the method set_data, but i just want the method to be slightly different for the trait different traits

In this case, you could implement the trait for all types, and make the setter method a no-op on types which currently don't implement the trait.

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.