6

When attempting to answer this question, I wrote this code:

trait MyTrait {
    type A;
    type B;
}

trait WithFoo: MyTrait {
    fn foo(a: Self::A) -> Self::B;
}

impl<T, U: MyTrait<A = T, B = T>> WithFoo for U {
    fn foo(a: T) -> T {
        a
    }
}

struct S1;

impl MyTrait for S1 {
    type A = u32;
    type B = f32;
}

impl WithFoo for S1 {
    fn foo<T>(a: Self::A) -> Self::B {
        a as f32
    }
}

struct S2;

impl MyTrait for S2 {
    type A = u32;
    type B = u32;
}

fn main() {
    S1::foo(42);
    S2::foo(42);
}

playground

This fails to compile with the following error:

error[E0119]: conflicting implementations of trait `WithFoo` for type `S1`:
  --> src/main.rs:23:1
   |
10 | impl<T, U: MyTrait<A = T, B = T>> WithFoo for U {
   | ----------------------------------------------- first implementation here
...
23 | impl WithFoo for S1 {
   | ^^^^^^^^^^^^^^^^^^^ conflicting implementation for `S1`

According to these answers this error occurs even though type S1 doesn't fit the impl trait bounds when the compiler can't be sure that some future blanket impl would cause S1 to suddenly match the bounds.

However in this case it is impossible that S1 could ever implement MyTrait with A == B since it already implements MyTrait with A != B. Is the error a limitation of the current compiler implementation that might conceivably be lifted at some later point or is there something else I'm missing?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Jmb
  • 18,893
  • 2
  • 28
  • 55

0 Answers0