diff --git a/README.md b/README.md index 8aeb2b13..ad7f0a9c 100644 --- a/README.md +++ b/README.md @@ -771,6 +771,15 @@ fn op_mul(self: Point, other: Point) -> Point { } ``` +Methods of a trait can be called directly via `Trait::method`. MoonBit will infer the type of `Self` and check if `Self` indeed implements `Trait`, for example: + +```rust +fn init { + println(Show::to_string(42)) + debug(Compare::compare(1.0, 2.5)) +} +``` + MoonBit provides the following useful builtin traits: ```rust @@ -819,6 +828,23 @@ fn ToMyBinaryProtocol::to_my_binary_protocol(x: String, b: Buffer) { ... } When searching for the implementation of a trait, extension methods have a higher priority, so they can be used to override ordinary methods with undesirable behavior. Extension methods can only be used to implement the specified trait. They cannot be called directly like ordinary methods. Furthermore, *only the package of the type or the package of the trait can implement extension methods*. For example, only `@pkg1` and `@pkg2` are allowed to implement an extension method `@pkg1.Trait::f` for type `@pkg2.Type`. This restriction ensures that MoonBit's trait system is still coherent with the extra flexibility of extension methods. +To involke an extension method directly, use the `Trait::method` syntax. + +```rust +trait MyTrait { + f(Self) +} + +fn MyTrait::f(self: Int) { + println("Got Int \(self)!") +} + +fn init { + MyTrait::f(42) +} +``` + + ## Automatically derive builtin traits MoonBit can automatically derive implementations for some builtin traits: diff --git a/zh-docs/README.md b/zh-docs/README.md index 53973558..761b1620 100644 --- a/zh-docs/README.md +++ b/zh-docs/README.md @@ -722,6 +722,15 @@ fn op_mul(self: Point, other: Point) -> Point { } ``` +接口中的方法可以用 `Trait::method` 的语法来直接调用。MoonBit 会推导 `Self` 的具体类型,并检查 `Self` 是否实现了 `Trait`: + +```rust +fn init { + println(Show::to_string(42)) + debug(Compare::compare(1.0, 2.5)) +} +``` + Moonbit 提供下列实用的内建接口: ```rust @@ -778,6 +787,22 @@ fn ToMyBinaryProtocol::to_my_binary_protocol(x: String, b: Buffer) { ... } 例如,只有 `@pkg1` 和 `@pkg2` 能为类型 `@pkg2.Type` 定义拓展方法 `@pkg1.Trait::f`。 这一限制使得 MoonBit 的接口系统在加入拓展方法这一灵活的机制后,依然是一致的。 +如果需要直接调用一个拓展方法,可以使用 `Trait::method` 语法。例如: + +```rust +trait MyTrait { + f(Self) +} + +fn MyTrait::f(self: Int) { + println("Got Int \(self)!") +} + +fn init { + MyTrait::f(42) +} +``` + ## 自动实现内建接口 Moonbit 可以自动生成一些内建接口的实现: