E4135

E4135#

不一致的 impl 实现:实现具有不同的约束。

当实现一个特征为类型时,所有实现都必须具有相同的约束。如果两个约束有交集,那么对于满足这两个约束的类型,使用哪个实现是不清楚的。

错误示例#

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
}

建议#

解决这个问题的一种方法是选择其中一个实现并删除另一个:

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

如果要为两个约束实现特征,您可以创建一个新特征,将这两个约束组合在一起:

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

并手动为满足约束 (ByteSizeWordSize) 的所有类型实现特征。