Skip to content

Commit

Permalink
doc: add ref / option / result
Browse files Browse the repository at this point in the history
  • Loading branch information
peter-jerry-ye committed Dec 16, 2024
1 parent f6aaa82 commit b147982
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 0 deletions.
27 changes: 27 additions & 0 deletions next/language/fundamentals.md
Original file line number Diff line number Diff line change
Expand Up @@ -207,6 +207,33 @@ Tuples can be accessed via pattern matching or index:
:end-before: end tuple 2
```

### Ref

A `Ref[T]` is a mutable reference containing a value `val` of type `T`.

It can be constructed using `{ val : x }`, and can be accessed using `ref.val`. See [struct](#struct) for detailed explanation.

```{literalinclude} /sources/language/src/builtin/top.mbt
:language: moonbit
:start-after: start ref 1
:end-before: end ref 1
```

### Option and Result

`Option` and `Result` are the most common types to represent a possible error or failure in MoonBit.

- `Option[T]` represents a possibly missing value of type `T`. It can be abbreviated as `T?`.
- `Result[T, E]` represents either a value of type `T` or an error of type `E`.

See [enum](#enum) for detailed explanation.

```{literalinclude} /sources/language/src/builtin/top.mbt
:language: moonbit
:start-after: start option result 1
:end-before: end option result 1
```

### Array

An array is a finite sequence of values constructed using square brackets `[]`, with elements separated by commas `,`. For example:
Expand Down
28 changes: 28 additions & 0 deletions next/sources/language/src/builtin/top.mbt
Original file line number Diff line number Diff line change
Expand Up @@ -202,3 +202,31 @@ let moon_pkg_json_example : Json = {
"test-import": ["moonbitlang/core/random"],
}
// end json 1

// start ref 1
let a : Ref[Int] = { val : 100 }

test {
a.val = 200
assert_eq!(a.val, 200)
a.val += 1
assert_eq!(a.val, 201)
}
// end ref 1

// start option result 1
test {
let a : Option[Int] = None
let b : Option[Int] = Some(42)
let c : Result[Int, String] = Ok(42)
let d : Result[Int, String] = Err("error")
match a {
Some(_) => assert_true!(false)
None => assert_true!(true)
}
match d {
Ok(_) => assert_true!(false)
Err(_) => assert_true!(true)
}
}
// end option result 1

0 comments on commit b147982

Please sign in to comment.