diff --git a/next/language/fundamentals.md b/next/language/fundamentals.md index 220b0909..5bc10301 100644 --- a/next/language/fundamentals.md +++ b/next/language/fundamentals.md @@ -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: diff --git a/next/sources/language/src/builtin/top.mbt b/next/sources/language/src/builtin/top.mbt index 138310e0..e753b731 100644 --- a/next/sources/language/src/builtin/top.mbt +++ b/next/sources/language/src/builtin/top.mbt @@ -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 \ No newline at end of file