E4073

E4073#

不能为外来特征定义默认实现。

这是 Moonbit 中 特质和类型的孤儿规则 的推论。默认实现可以看作是针对所有可能类型的特征,包括当前软件包内部或外部定义的类型。因此,只有在特征的包装包中定义默认实现,否则它将违反孤儿规则。

错误示例#

假设你在模块 username/hello 下的包 a 中定义了一个特征 T

a/a.mbt:

// We need the trait to be pub(open) so that it can be implemented from outside.
pub(open) trait T {
  f(Self) -> Int
}

当你想在另一个包中为特征定义默认实现时,命名为 b

b/moon.pkg.json:

{
  "import": [
    "username/hello/a"
  ]
}

b/b.mbt:

impl @a.T with f(self : Self) -> Int {
  //           ^
  // Error: Cannot provide default implementation for trait @a.T from package a
  ignore(self)
  0
}

建议#

要修复这个错误,您可以将 trait 的定义和它的默认实现移到同一个包中。假设你可以把 trait 的定义移到包 b 中:

b/b.mbt:

pub(open) trait T {
  f(Self) -> Int
}

impl T with f(self : Self) -> Int {
  ignore(self)
  0
}