E4061

E4061#

无法为类型和特征(trait)都定义在其他包中的情况实现该特征(trait)

MoonBit 遵循孤儿规则(orphan rule),这意味着你只能在以下情况下实现特征(trait):

特征(trait)

类型

允许实现?

当前包

当前包

其他包

当前包

当前包

其他包

其他包

其他包

See the Access control of methods and trait implementations section of the MoonBit documentation for more information.

错误示例#

Suppose you have type A and trait B defined in package a in module username/hello:

a/a.mbt:

pub(all) type A Int
pub(open) trait B {
  to_int(Self) -> Int
}

a/moon.pkg.json:

{}

Now, if you want to implement trait @a.B for type @a.A:

b/moon.pkg.json:

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

b/b.mbt:

impl @a.B for @a.A with to_int(self : @a.A) -> Int {
  //                    ^~~~~~
  // Error: Cannot define method to_int of trait @a.B from package a for type @a.A from package a
  self._
}

MoonBit will report an error.

建议#

You can move either the trait or type into the current package where the implementation is in. If that is not possible, you can create a new type over the type you wish to implement the trait for, and then implement the trait for the new type:

b/b.mbt:

type WrapA @a.A

impl @a.B for WrapA with to_int(self : WrapA) -> Int {
  ...
}