E4135

E4135#

Inconsistent impl of trait: implementations have different constraints.

When implementing a trait for a type, all implementations must have the same constraints. If the two constraints has intersection, then it would be unclear which implementation to use for types that satisfy both constraints.

错误示例#

trait ByteSize { byte_size() -> Int}
impl ByteSize for Byte with byte_size() { 1 }
impl ByteSize for Int with byte_size() { 4 }

trait WordSize { word_size() -> Int }
impl WordSize for Float with word_size() { 1 }
impl WordSize for Double with word_size() { 2 }

trait Size { size(Self) -> Int }

impl[T : ByteSize] Size for Array[T] with size(self) {
  self.length() * T::byte_size()
}

impl[T : WordSize] Size for Array[T] with size(self) {
//<~~~~~~~~~~~~~~~
// Error: Inconsistent `impl` of trait Size for Array at 11:1 and 15:1:
//   type parameters of implementations have different constraints
  self.length() * T::word_size() * 4
}

建议#

One way to resolve this issue is to pick one of the implementations and remove the other:

// Remove the implementation for WordSize
// impl[T : WordSize] Size for Array[T] with size(self) {
//   self.length() * T::word_size() * 4
// }

If you want to implementation for both constraints, you can create a new trait that combines the constraints:

trait ByteWordSize {
  byte_size() -> Int
  word_size() -> Int
}

And manually implement the trait for all the types that satisfy the constraints (ByteSize or WordSize).