Method and Trait
DRANK

MoonBit provides a trait system for overloading/ad-hoc polymorphism. Traits declare a list of operations, which must be supplied when a type wants to implement the trait. Traits can be declared as follows:In the body of a trait definition, a special type Self is used to refer to the type that implements the trait.Extending traitsA trait can depend on other traits, for example:pub(open) trait Position { pos(Self) -> (Int, Int) } pub(open) trait Draw { draw(Self, Int, Int) -> Unit } pub(open) trait Object: Position + Draw {} Implementing traitsTo implement a trait, a type must explicitly provide all the methods required by the trait using the syntax impl Trait for Type with method_name(...) { ... }. For example:pub(open) trait MyShow { to_string(Self) -> String } struct MyType {} pub impl MyShow for MyType with to_string(self) { ... } struct MyContainer[_] {} // trait implementation with type parameters. // `[X : Show]` means the type parameter `X` must implement `Show`, // this…

docs.moonbitlang.com
Related Topics: