Skip to content

Commit

Permalink
Merge pull request #146 from moonbitlang/call-trait-method
Browse files Browse the repository at this point in the history
add doc for [Trait::method] call syntax
  • Loading branch information
bzy-debug authored Feb 6, 2024
2 parents d590573 + 8ebb182 commit 4ee5d1d
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 0 deletions.
26 changes: 26 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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:
Expand Down
25 changes: 25 additions & 0 deletions zh-docs/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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 可以自动生成一些内建接口的实现:
Expand Down

0 comments on commit 4ee5d1d

Please sign in to comment.