Skip to content

Commit

Permalink
add doc for type alias
Browse files Browse the repository at this point in the history
  • Loading branch information
Guest0x0 committed Oct 21, 2024
1 parent 208b5a7 commit 4ff8730
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 0 deletions.
18 changes: 18 additions & 0 deletions moonbit-docs/docs/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -1206,6 +1206,24 @@ fn init {
}
```

### Type alias
MoonBit supports type alias via the syntax `typealias Name = TargetType`:

```moonbit
pub typealias Index = Int
// type alias are private by default
typealias MapString[X] = Map[String, X]
```

unlike all other kinds of type declaration above, type alias does not define a new type,
it is merely a type macro that behaves exactly the same as its definition.
So for example one cannot define new methods or implement traits for a type alias.

Type alias can be used to perform incremental code refactor.
For example, if you want to move a type `T` from `@pkgA` to `@pkgB`,
you can leave a type alias `typealias T = @pkgB.T` in `@pkgA`, and **incrementally** port uses of `@pkgA.T` to `@pkgB.T`.
The type alias can be removed after all uses of `@pkgA.T` is migrated to `@pkgB.T`.

## Pattern Matching

We have shown a use case of pattern matching for enums, but pattern matching is not restricted to enums. For example, we can also match expressions against Boolean values, numbers, characters, strings, tuples, arrays, and struct literals. Since there is only one case for those types other than enums, we can pattern match them using `let` binding instead of `match` expressions. Note that the scope of bound variables in `match` is limited to the case where the variable is introduced, while `let` binding will introduce every variable to the current scope. Furthermore, we can use underscores `_` as wildcards for the values we don't care about, use `..` to ignore remaining fields of struct or elements of array.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1176,6 +1176,19 @@ fn init {
}
```

### 类型别名
MoonBit 支持类型别名。声明类型别名的语法是 `typealias Name = TargetType`:

```moonbit
pub typealias Index = Int
// 类型别名默认是私有的
typealias MapString[X] = Map[String, X]
```

和上面提到的所有其他形式的类型定义不同,类型别名不会真的创建一个新的类型,它只是一个类型层面的宏,在所有地方都等价于它的定义。所以用户无法给类型别名定义方法或是实现接口。

类型别名可以用于代码的渐进式重构。例如,如果要把 `@pkgA` 中的类型 `T` 迁移到 `@pkgB`,可以现在 `@pkgA` 中留下一个类型别名 `typealias T = @pkgB.T`,然后**渐进式**地逐步把代码仓库各处的 `@pkgA.T` 替换成 `@pkgB.T`。直到所有替换完成,再删除 `@pkgA` 中的类型别名。

## 模式匹配

我们已经展示了如何对枚举进行模式匹配,但模式匹配并不仅限于枚举。
Expand Down

0 comments on commit 4ff8730

Please sign in to comment.