Is it a compiler limitation that reports “conflicting implementations of trait” even though it's impossible for a type to implement a trait?

瘦欲@ 提交于 2019-12-23 10:04:57

问题


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?

来源:https://stackoverflow.com/questions/55630220/is-it-a-compiler-limitation-that-reports-conflicting-implementations-of-trait

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!