E4059

E4059#

Cannot define method for foreign type.

Foreign types are types that is not defined in the current package. MoonBit only allows defining methods or implementing traits for types that are defined in the current package.

错误示例#

In package a:

pub type A Int

In package b:

fn f(self : @a.A) -> Int { // Error: Cannot define method f for foreign type @a.A
  0
}

Defining methods for builtin types, or types in standard library, is another frequent case of this error:

fn f(self : Int) -> Int { // Error: Cannot define method f for foreign type Int
  0
}

建议#

You can either move the type definition to the current package:

pub type A Int

fn f(self : A) -> Int {
  0
}

Or use new type to wrap the foreign type:

pub type WrapA @a.A

fn f(self : WrapA) -> Int {
  ignore(self._) // Use `._` to access the wrapped value if @a.A is public
  0
}