E4061

E4061#

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

MoonBit 遵循孤儿规则(orphan rule),这意味着你只能在以下情况下实现特征(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/top.mbt:

///|
pub(all) struct A(Int)

///|
pub(open) trait B {
  to_int(Self) -> Int
}

a/moon.pkg:


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

b/moon.pkg:

import {
  "username/hello/a",
}

b/top.mbt:

///|
impl @a.B for @a.A with to_int(self : @a.A) -> Int {
  self.0
}

MoonBit 会报错。

建议#

你可以将特征或类型移动到包含该实现的包中。如果无法这样做,请为目标类型创建一个包装类型,然后为这个包装类型实现该特征:

b/top.mbt:

///|
priv struct WrapA(@a.A)

///|
impl @a.B for WrapA with to_int(self : WrapA) -> Int {
  let _ = self.0
  0
}

///|
test {
  let value = WrapA(@a.A(1))
  inspect(value.to_int(), content="0")
}