Skip to content

Commit

Permalink
add doc for question operator
Browse files Browse the repository at this point in the history
  • Loading branch information
Guest0x0 committed Jan 9, 2024
1 parent c46fc64 commit 9c75588
Show file tree
Hide file tree
Showing 2 changed files with 86 additions and 0 deletions.
43 changes: 43 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -837,6 +837,49 @@ fn init {
}
```

## The question operator
MoonBit features a convenient `?` operator for error handling.
The `?` postfix operator can be applied to expressions of type `Option` or `Result`.
When applied to expression `t : Option[T]`, `t?` is equivalent to:

```rust
match t {
None => { return None }
Some(x) => x
}
```

When applied to expression `t: Result[T, E]`, `t?` is equivalent to:

```rust
match t {
Err(err) => { return Err(err) }
Ok(x) => x
}
```

The question operator can be used to combine codes that may fail or error elegantly:

```rust
fn may_fail() -> Option[Int] { ... }

fn f() -> Option[Int] {
let x = may_fail()?
let y = may_fail()?.lsr(1) + 1
if y == 0 { return None }
Some(x / y)
}

fn may_error() -> Result[Int, String] { ... }

fn g() -> Result[Int, String] {
let x = may_error()?
let y = may_error()? * 2
if y == 0 { return Err("divide by zero") }
Ok(x / y)
}
```

## MoonBit's build system

The introduction to the build system is available at [MoonBit's Build System Tutorial](./build-system-tutorial.md).
43 changes: 43 additions & 0 deletions zh-docs/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -796,6 +796,49 @@ fn init {
}
```

## 问号操作符
MoonBit 提供一个便捷的 `?` 操作符,用于错误处理。
`?` 是一个后缀运算符。它可以作用于类型为 `Option``Result` 的表达式。
被应用在表达式 `t : Option[T]` 上时,`t?` 等价于:

```rust
match t {
None => { return None }
Some(x) => x
}
```

被应用在表达式 `t : Result[T, E]` 上时,`t?` 等价于:

```rust
match t {
Err(err) => { return Err(err) }
Ok(x) => x
}
```

问号操作符可以用于优雅地组合多段可能失败或产生错误的程序:

```rust
fn may_fail() -> Option[Int] { ... }

fn f() -> Option[Int] {
let x = may_fail()?
let y = may_fail()?.lsr(1) + 1
if y == 0 { return None }
Some(x / y)
}

fn may_error() -> Result[Int, String] { ... }

fn g() -> Result[Int, String] {
let x = may_error()?
let y = may_error()? * 2
if y == 0 { return Err("divide by zero") }
Ok(x / y)
}
```

## MoonBit 的构建系统

构建系统的介绍可以在 [MoonBit 的构建系统教程](./build-system-tutorial.md) 中找到。

0 comments on commit 9c75588

Please sign in to comment.