即使类型不可能实现特征,还是报告“特征的冲突实现”的编译器限制?

时间:2019-04-11 10:23:11

标签: rust traits

当尝试回答this question时,我编写了以下代码:

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

这无法编译并出现以下错误:

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`

根据these answers,即使在编译器无法确定将来是否有某些掩盖的情况下,即使类型S1不符合impl特征范围,也会发生此错误impl将导致S1突然与边界匹配。

但是在这种情况下,S1不可能用MyTrait实现A == B,因为它已经用MyTrait实现了A != B。该错误是当前编译器实现的限制,可以想象稍后会取消该错误,还是我遗漏了其他内容?

0 个答案:

没有答案