The compiler sees conflicting implementations where they do not exists

PLAYGROUND:(Playground)

In the example below, not for my structure, not for My trait, T do not need to implement Into. This mistake seems to me Absurd. I would like to know the general solutions to this error. AND THE MAIN THING: does this error appear because of the compiler's guesses that T implements Into?

Code:

fn main() {}

trait MyTrait{}

struct MyStruct{}

impl<T> TryFrom<T> for MyStruct 
where
    T: MyTrait
{
   
}

Error:

Compiling playground v0.0.1 (/playground)
error[E0119]: conflicting implementations of trait TryFrom<_>for type MyStruct
 --> src/main.rs:8:1
  |
8 | impl<T> TryFrom<T> for MyStruct 
  | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  |
  = note: conflicting implementation in crate core:
          - impl<T, U> TryFrom<U> for T
            where U: Into<T>;

For more information about this error, try rustc --explain E0119.
error: could not compile playground due to previous error

The reason for this is because they're is a blanket impl in the standard library for any T -> T identity conversion using From; which transitively provides Into<MyStruct> for MyStruct, which again transitively provides TryFrom<MyStruct> for MyStruct.

The conflict is when your generic T is filled in by your own struct MyStruct.

3 Likes

But T has to implement MyTrait,but MyStrust doesn't.

There can still be conflicting implementations of TryFrom. Imagine you have a type T that implements MyTrait and Into<MyStruct>. Which version of TryFrom is the compiler supposed to use? Rust's efforts in mitigating the problem of conflicting trait implementations can be found in the impl specialization RFC, but it won't land anytime soon.

2 Likes

Thank you,it helped me, As a result, I decided to either use TryFrom<Wrapper> istead of TryFrom or use build function to create an instance.

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.