MoonBit cheats.mbt

MoonBit Language Cheat Sheet

17 sections · 688 entries · updated 2026-12-03

Hello, MoonBit#

MoonBit is an end-to-end language toolchain for cloud and edge computing that compiles to four backends: Wasm, Wasm GC, JavaScript, and Native. It packs algebraic data types, pattern matching, traits, checked error handling, and async into a compact syntax, and ships with its own build system, package manager, testing, and documentation tools.

This page is a single-page cheat sheet: it lists syntax and standard library usage by topic, aimed at people who already program and need a quick lookup. The syntax follows moonc 1.0.0-rc1, and key examples are verified by local compilation.

Thirty-second start#

fn main {
  println("Hello, MoonBit!")
}
# Linux / macOS
curl -fsSL https://cli.moonbitlang.com/install/unix.sh | bash

# Windows (PowerShell)
Set-ExecutionPolicy RemoteSigned -Scope CurrentUser; irm https://cli.moonbitlang.com/install/powershell.ps1 | iex
moon new hello      # Create a module
cd hello
moon run cmd/main   # Run
moon test           # Run tests

Try it online: T · Download and IDE setup: M

Language features#

  • Expression-oriented: if, match, and loops all return values; the last expression in a function body is the return value.
  • Reference semantics by default: arrays, Maps, and structs with mut fields are passed by reference; primitive types become mutable explicitly via Ref[T].
  • No lifetime annotations: there is a GC and no ownership system, so the learning curve is gentler than Rust.
  • Checked errors: functions declare possible errors with raise E, and the compiler forces callers to handle or propagate them.
  • Multiple backends: a single module can mix native and wasm/js packages that share a domain model.
  • Fast compilation, small output: official benchmarks emphasize compile speed and Wasm artifact size.

Legend#

Symbol Meaning
L Links to the language reference (docs.moonbitlang.com)
T Links to the online playground (tour.moonbitlang.com)
A Links to the standard library API (mooncakes.io)
P Links to the mooncakes package page
G Links to a tutorial
D Links to the toolchain docs
M Links to the MoonBit website
错 Bad example or common pitfall
弃 Deprecated; do not use in new code
验 Experimental feature; may change
荐 Recommended usage
1 Footnote

Conventions#

  • ... in code blocks denotes omitted implementation details.
  • T? is shorthand for Option[T]; T can be any type.
  • Items marked 验 may change between versions; after upgrading the toolchain, rely on moon check.
  • Type names default to UpperCamel, values and functions to lower_snake, and enum constructors must start uppercase.

Data structures#

MoonBit defines all named types with three keywords: struct, enum, and type. There are no classes, inheritance, or null.

Defining types#

Example Description
struct S { x : Int; y : String } Defines a struct; fields are immutable by default.
struct S { mut x : Int } mut fields can be modified in place; structs with mut fields are passed by reference.
struct P(Int, String) Tuple struct, accessed via .0, .1; good for lightweight wrappers.
struct H((Int) -> Unit) Single-field newtype, often used to give a function type a name.
struct S {} Empty struct; construct with S::{} ({} is parsed as an empty Map).
pub struct S { x : Int } Readable and pattern-matchable outside the package, but not constructible.
pub(all) struct S { x : Int } Readable and constructible outside the package; use this when external code needs S::{ x: 1 }.
enum E { A; B(Int); C(x~ : Int) } Defines an enum (algebraic data type): constructors with no arguments, positional arguments, or labeled arguments.
enum E[T] { Leaf(T); Node(E[T], E[T]) } Generic recursive enum; constructors must start uppercase.
#derive(Debug, Eq, Compare) Derives trait implementations before the type declaration.
type UserId = Int Type alias with zero runtime cost; fully equivalent to Int and cannot be used as a distinct type.
priv struct S Explicitly private (visible within the package); top-level declarations are private by default.
#derive(Debug, Eq, Compare)
pub(all) struct Point {
  x : Int
  mut y : Int
}

pub(all) enum Shape {
  Circle(radius~ : Double)
  Rect(width~ : Double, height~ : Double)
  Empty
}

Bindings and constants#

Example Description
let x = 1 Immutable binding; the type is usually inferred.
let mut y = 2<br>y = y + 1 Mutable binding, only for local variables; globals and fields need an explicit mut.
let x : Int64 = 1 Explicit type annotation; integer literals are overloaded by target type.
let (a, b) = (1, 2) Tuple destructuring binding.
let Some(x) = opt 错 A refutable pattern cannot be bound directly; use match or guard.
const PI : Double = 3.14159 Compile-time constant; the type must be annotated.
let greeting : String = "hi" Top-level immutable global value; usually needs a type annotation.
let mut counter : Int = 0 错 A top-level let cannot be mut; for mutable state use Ref or a struct field.

Construction and access#

Example Description
Point::{ x: 1, y: 2 } Construct a struct; the Type:: prefix can be omitted when the type is known.
{ x: 1, y: 2 } Shorthand when the target type is known (function arguments, return values, annotated let).
Point::{ ..p, y: 3 } Struct update: copy the remaining fields of p, overriding y.
p.x Named field access.
p.0 Positional field access on a tuple struct.
p.y = 3 Legal only when the field is declared mut and p is writable.
Shape::Circle(radius=1.0) Enum constructor; labeled arguments use 名字= or 名字~.
Shape::Empty A no-argument constructor is just a value.
(1, "a") Tuple; element types may differ.
() The unit value, which is also the unit type; functions without a return value return it.
[1, 2, 3] Array literal, type Array[Int].
{ "a": 1, "b": 2 } Map literal, type Map[String, Int].
Ref(0) Mutable cell; read and write via r.val.

Built-in types#

Type Description
Int 32-bit signed integer (alias of Int32).
Int64 / UInt64 64-bit integer.
UInt 32-bit unsigned integer (UInt32).
Int16 / UInt16 16-bit integer.
Byte 8-bit unsigned byte.
Double / Float 64-bit / 32-bit floating point.
Bool true / false.
Char Unicode scalar value; literals 'a', '\n', '中'.
String Immutable UTF-16 string; s[i] returns a code unit (UInt16).
StringView String slice view, obtained via s[:], zero-copy.
Bytes / BytesView Immutable byte sequence and view; literal b"abc".
Array[T] Growable array with reference semantics.
FixedArray[T] Fixed-length array; the length does not change after creation.
ArrayView[T] Array view, obtained via a[:] or a[1:3].
Map[K, V] Hash table; iteration order is undefined, so do not rely on insertion order.
Set[T] Hash set from moonbitlang/core/hashset, written @hashset.HashSet[T].
Option[T] / T? Some(v) or None, replacing null.
Result[T, E] Ok(v) or Err(e), for explicit error values.
Unit Unit type; the value is written ().
Ref[T] Mutable reference cell, used to make primitive types modifiable by reference.

> Note 错 — String is UTF-16, so s.length() counts code units, not characters; emoji and other supplementary-plane characters take two code units. To count by character, use s.char_length().

Functions and behavior#

Functions are the basic unit of organization in MoonBit: top-level functions, methods, and closures all share the same fn syntax.

Defining functions#

Example Description
fn f(x : Int) -> Int { x + 1 } Plain function; the last expression is the return value.
fn f() -> Unit { } No return value; -> Unit can be omitted.
fn main { } Program entry point; no parameters, no return value.
pub fn f() -> Int { 1 } Exported outside the package; defaults to priv.
fn[T] id(x : T) -> T { x } Generic parameters go after fn</strong>, not after the function name.
fn[A, B] pair(a : A, b : B) -> (A, B) { (a, b) } Multiple type parameters.
fn[T : Show + Eq] f(x : T) -> Unit { } Generics with trait bounds.
fn f(x~ : Int) -> Int { x } Required labeled argument; callers must write x=.
fn f(x? : Int = 0) -> Int { x } Optional labeled argument with a default value.
fn f(x : Int, y? : Int = 1) -> Int { x + y } Positional and labeled arguments can be mixed; labeled arguments come last.
fn f() -> Int raise MyError { ... } Declares that MyError may be thrown; errors propagate upward automatically.
fn f() -> Int raise { ... } When the exact error type doesn't matter, write just raise.
async fn f() -> Int { ... } Async function; no await at the call site, you get the result directly.
extern "C" fn f(x : Int) -> Int = "sym" External function declaration; see FFI.
fn f() -> Int { return 1 } return is for early returns; the final expression need not use return.
/// Compute factorial; `///` comments go into the docs and are exercised by tests.
pub fn factorial(n : Int) -> Int {
  if n <= 1 {
    1
  } else {
    n * factorial(n - 1)
  }
}

> Top-level functions are mutually recursive by default and need no forward declarations; local fns can also recurse.

Calls and labeled arguments#

Example Description
f(1, 2) Positional call.
f(x=1, y=2) Labeled arguments may be given in any order.
f(x~, y~) Shorthand: x=x, y=y, passing variables of the same name directly.
f(1) Omits optional arguments that have defaults.
p.area() Method-call syntax; equivalent to Shape::area(p).
Shape::area(p) Explicit qualified call, avoiding ambiguity with same-named methods.
xs.map(fn(x) { x * 2 }) Pass a closure as a value.
xs.map(double) Named functions are first-class values too.
expr |> f Pipe: passes the left result as the first argument of the right function.
expr |> x => { x + 1 } Pipe with an anonymous function; x => expr is closure shorthand.

Methods and trait implementations#

Example Description
fn Type::method(self : Type) -> Int { ... } Adds an inherent method to a type, callable as value.method().
fn Type::new(x : Int) -> Type { ... } Associated function (no self), called as Type::new(1).
impl Trait for Type with method(self) { ... } Implements one trait method; multiple methods need multiple impl blocks.
pub impl Trait for Type with method(self) { ... } Exports the trait implementation so generic code outside the package can use it.
pub extend Type with Trait::{method} Promotes a trait method to method-call syntax (value.method()).
impl Add for Vec with add(self, other) { ... } Operator overloading; see Generics and traits.
pub(all) struct Rect {
  width : Double
  height : Double
}

/// Inherent method: the first parameter is self.
pub fn Rect::area(self : Rect) -> Double {
  self.width * self.height
}

/// Associated function: no self.
pub fn Rect::square(side : Double) -> Rect {
  { width: side, height: side }
}

test "methods" {
  let r = Rect::square(2.0)
  inspect(r.area(), content="4")
}

Closures#

Example Description
fn(x) { x * 2 } Anonymous function; parameter types can be inferred.
fn(x : Int) -> Int { x * 2 } Fully annotated anonymous function.
x => x * 2 Single-expression shorthand, common with |> and higher-order functions.
let f = fn(x) { x + 1 } Closures are values: bind them, pass them, return them.
fn() { counter.val = counter.val + 1 } Closures capture outer variables; use Ref for captured mutable state.
test "closures" {
  let double = fn(x : Int) -> Int { x * 2 }
  inspect([1, 2, 3].map(double), content="[2, 4, 6]")
  inspect([1, 2, 3].map(x => x + 1), content="[2, 3, 4]")
}

Special functions#

Example Description
test "name" { ... } Test block; moon test collects and runs it.
test { ... } Anonymous test block; the name is generated automatically.
async test "name" { ... } Async test.
fn main { ... } Executable package entry point, paired with pkgtype(kind: "executable").
bench "name" { ... } Benchmark block, run with moon bench.
extern "js" fn f() -> Int = "() => 1" JS-backend FFI; the body is JavaScript source.
extern "C" fn f(x : Int) -> Int = "c_symbol" Native-backend FFI.

> Pitfall 错 — Top-level functions are mutually recursive by default, but local functions that are mutually recursive need a forward declaration; if you hit an "unbound identifier" error, move one of them to top level.

Control flow#

if, match, and loops are all expressions; they can appear on the right side of an assignment or as a function return value.

Conditionals#

Example Description
if x > 0 { "正" } else { "非正" } The if expression returns the common type of both branches.
if a { 1 } else if b { 2 } else { 3 } else if chain.
if cond { do_something() } Without else it returns Unit and can only be used as a statement.
let x = if cond { 1 } else { 2 } Assign a conditional expression to a variable.
guard x > 0 else { return } Guard: runs the else block when the condition fails; it can yield a fallback value or diverge with return/raise.
guard opt is Some(v) else { fail("空值") } Guard plus pattern matching; binds v in place on success.
fn sign(x : Int) -> String {
  if x > 0 {
    "positive"
  } else if x < 0 {
    "negative"
  } else {
    "zero"
  }
}

Pattern matching#

Example Description
match x { 0 => "零"; _ => "非零" } Basic match; branches are separated by newlines or ;.
match opt { Some(v) => v; None => 0 } Destructure Option.
match e { Circle(r) => ...; Rect(w, h) => ... } Destructure enum constructors.
match p { { x, y } => x + y } Destructure struct fields.
match xs { [] => 0; [x, .. rest] => x } Array pattern; .. rest binds the remainder.
match c { 'a'..='z' => 1; _ => 0 } Range pattern.
match x { A | B => 1; _ => 0 } Or pattern; several patterns share a branch.
Some(x) if x > 0 => x Branch guard, written before =>.
match t { (a, b) => a + b } Tuple destructuring.
match s { "yes" => true; _ => false } String literal pattern.
pub(all) enum Shape {
  Circle(radius~ : Double)
  Rect(width~ : Double, height~ : Double)
  Empty
}

fn area(s : Shape) -> Double {
  match s {
    Circle(radius~) => 3.14159 * radius * radius
    Rect(width~, height~) => width * height
    Empty => 0.0
  }
}

Loops#

Example Description
for x in xs { ... } Iterate over arrays, Maps, strings, and iterators.
for i, x in xs { ... } Get the index and element together.
for i in 0..<n { ... } Half-open range; usable in for .. in and list comprehensions.
for i in 0..<=n { ... } Ascending inclusive range (the compiler also accepts 0..=n).
for i in n>..0 { ... } Descending: excludes the start, includes the end.
for i in n>=..0 { ... } Descending: includes both start and end.
[ for x in xs => x * x ] List comprehension; an if filter can precede =>.
for k, v in map { ... } Iterate over Map key-value pairs; order is undefined.
while cond { ... } Conditional loop.
while cond { ... } nobreak { ... } The nobreak block runs when the loop ends normally (without hitting break).
for i = 0 { ... continue i + 1 ... break i } Functional loop: state is carried explicitly, and break yields the result.
for i = 0; i < n; i = i + 1 { ... } C-style header; use , to carry multiple states.
for i = 0, sum = 0; i <= n; i = i + 1, sum = sum + i { } nobreak { sum } Multiple states plus the value taken when the loop ends normally.
break / continue Break out of / continue the current loop; break value makes the loop expression return value.
outer~: for x in xs { ... break outer~ v } Labeled loop; break or continue across nested levels.
test "loops" {
  // Range loop
  let mut sum = 0
  for i in 0..<10 {
    sum = sum + i
  }
  inspect(sum, content="45")

  // Iterate with indices
  let names = ["a", "b"]
  let mut out = ""
  for i, name in names {
    out = out + "\{i}:\{name};"
  }
  inspect(out, content="0:a;1:b;")

  // Functional loop: put state in the loop header
  let total = for i = 0, acc = 0 {
    if i < 5 {
      continue i + 1, acc + i
    } else {
      break acc
    }
  }
  inspect(total, content="10")
}

> Note — The stateless functional loop loop { ... } is deprecated 弃; for an infinite loop write while true { ... }, and when you need state write for state = init { ... }.

Early return and divergence#

Example Description
return Return Unit from the function.
return value Return a value early.
raise MyError::Bad Raise an error; type-wise it is equivalent to diverging.
fail("message") Raise a generic Failure, often used in tests and prototypes.
abort("message") Terminate the program immediately; returns any type (Never).
panic() Trigger a panic, no arguments; naming a test test "panic ..." marks it as an expected crash.
defer cleanup() Runs when leaving scope, including on error, return, break, and continue; multiple defers run in reverse order.
errdefer cleanup() Runs only when the scope raises an error or an async task is cancelled.

> Idiom 荐 — Prefer expressions over return: use the result of if/match/loops directly as the return value. The code is shorter and less likely to miss a branch.

Pattern matching#

Patterns appear in match branches, guard, let destructuring, and is expressions. The compiler checks exhaustiveness: a missing branch is a hard error.

Pattern reference#

Pattern Description
_ Wildcard; matches any value without binding.
x Variable pattern; binds the whole value (starts lowercase).
42 / "ok" / 'a' / true Literal pattern.
Some(x) / None Option constructor pattern.
Ok(v) / Err(e) Result constructor pattern.
Circle(radius~) Enum constructor plus labeled field destructuring.
Circle(radius=r) Same as above, writing the field name explicitly.
Rect(w, h) Positional constructor destructuring.
Empty No-argument constructor pattern.
{ x, y } Struct field destructuring; the field name is the binding name.
{ x, .. } Take only some fields, ignoring the rest.
(a, b) Tuple destructuring.
[] / [x] / [x, .. rest] Array pattern; .. rest binds the remaining slice (ArrayView).
[first, .. _middle, last] Take the first and last elements, ignoring the middle.
A | B Or pattern; several patterns share one branch.
'a'..='z' Range pattern (characters, integers).
pat if cond Branch guard: match first, then test the condition.
x is Some(_) is expression; returns Bool and can be used directly in if/guard.

Using patterns in match#

fn describe(xs : Array[Int]) -> String {
  match xs {
    [] => "空"
    [x] => "一个元素:\{x}"
    [first, .. rest] if rest.length() > 2 => "长数组,首项 \{first}"
    [first, .. _] => "短数组,首项 \{first}"
  }
}
fn classify(c : Char) -> String {
  match c {
    '0'..='9' => "digit"
    'a'..='z' | 'A'..='Z' => "letter"
    ' ' | '\t' | '\n' => "space"
    _ => "other"
  }
}

Destructuring and guards#

Form Description
let (a, b) = (1, 2) Tuple destructuring; must be exhaustive.
guard p is { x, y } else { return } Struct destructuring plus guard; exits early on failure.
guard xs is [first, .. rest] else { ... } Array destructuring plus guard.
if opt is Some(v) { use(v) } is binds v inside if.
if r is Err(e) { log(e) } Check a Result branch.
match e { Circle(radius~) => radius; _ => 0.0 } When only one field matters, bind it directly via the label.
fn first_or_zero(xs : Array[Int]) -> Int {
  guard xs is [first, .. _] else { return 0 }
  first
}

test "is binding" {
  let opt : Int? = Some(3)
  if opt is Some(v) {
    inspect(v, content="3")
  }
}

> Note 错 — let Some(x) = opt is not a valid binding: let only accepts irrefutable patterns. For refutable destructuring use match, guard ... else, or if ... is.

> Idiom 荐 — Prefer match over nested if; putting "constructor + guard" on one line lets readers see every branch condition at a glance.

Generics and traits#

MoonBit has only two abstraction mechanisms: generics (compile-time monomorphization) and traits (behavioral constraints). There is no inheritance and no vtable syntax.

Generics#

Example Description
fn[T] id(x : T) -> T { x } Type parameters go after fn.
fn[A, B] pair(a : A, b : B) -> (A, B) { (a, b) } Multiple type parameters.
fn[T : Show] f(x : T) -> String { x.to_string() } Constrain a type parameter with a trait; + joins multiple bounds.
struct Box[T] { value : T } Generic struct.
enum Tree[T] { Leaf(T); Node(Tree[T], Tree[T]) } Generic recursive enum.
pub impl[T] Size for Box[T] with size(self) { ... } Generic trait implementation; the [T] after impl declares the type parameter.
#derive(Debug) The derived implementation automatically adds the same bounds to the fields.

Defining traits#

Example Description
trait T { method(Self) -> Int } Define a trait; method signatures omit fn</strong>, and Self refers to the implementing type.
pub trait T { ... } Export a trait; by default it can only be implemented in the current package.
pub(open) trait T { ... } Allow types outside the package to implement the trait.
trait T { f(Self) -> Int; g(Self) -> String } A trait can declare multiple methods.
impl T for S with f(self) { ... } Implement one method; multiple methods need multiple impl blocks.
pub impl T for S with f(self) { ... } Export the implementation so generic code outside the package can use it.
pub extend S with T::{f} Promote a trait method to s.f() method-call syntax.
T::f(value) Explicit qualified call, common in generic contexts.
pub trait Shape {
  area(Self) -> Double
  name(Self) -> String
}

pub(all) struct Circle {
  r : Double
}

pub impl Shape for Circle with area(self) {
  3.14159 * self.r * self.r
}

pub impl Shape for Circle with name(self) {
  "circle"
}

pub fn[T : Shape] describe(s : T) -> String {
  "\{T::name(s)}: \{T::area(s)}"
}

test "trait" {
  inspect(describe(Circle::{ r: 1.0 }).has_prefix("circle"), content="true")
}

Operator overloading#

Syntax trait and method Example
a + b Add::add Vec(1, 2) + Vec(3, 4)
a - b Sub::sub a - b
a * b Mul::mul a * 2
a / b Div::div a / 2
a % b Mod::mod a % 2
-a Neg::neg -a
a == b / a != b Eq::equal / not_equal p == q
a < b etc. Compare::compare p < q
a & b / a | b / a ^ b BitAnd::land / BitOr::lor / BitXOr::lxor Bitwise operations
a << n / a >> n Shl::shl / Shr::shr Shift
a[i] at Index read
a[i] = v set Index write
pub(all) struct Vec2(Int, Int)

pub impl Add for Vec2 with add(self, other) {
  Vec2(self.0 + other.0, self.1 + other.1)
}

test "operator" {
  let v = Vec2(1, 2) + Vec2(3, 4)
  inspect(v.0, content="4")
}

Deriving#

Derive Generated
#derive(Debug) Structured debug output, paired with @debug.to_string and debug_inspect.
#derive(Eq) == / !=, comparing field by field.
#derive(Compare) <, <=, >, >=; enums compare by declaration order.
#derive(Hash) Usable as a Map / Set key.
#derive(Default) Default::default(); an enum must have exactly one no-argument constructor.
#derive(ToJson) Serialize to JSON, paired with @json.to_json.
#derive(FromJson) Deserialize from JSON, paired with @json.from_json.
#derive(Arbitrary) Generate random values, used for property testing.
#derive(Debug, Eq, Compare, Hash, Default)
pub(all) struct Config {
  host : String
  port : Int
}

/// Deriving only generates the implementation; to make the method usable, promote it explicitly.
pub extend Config with Debug::{to_repr}

test "derive" {
  let c : Config = Default::default()
  inspect(c.port, content="0")
  inspect(@debug.to_string(c), content="{ host: \"\", port: 0 }")
}

> Note 错 — The old syntax that writes derive(...) after the type is deprecated 弃; put #derive(...) before the declaration. #derive(Show) is likewise deprecated; use Debug for debugging.

> Note 错 — Derived trait methods do not automatically appear in method calls; you need pub extend Type with Trait::{method} to use value.method() outside the package.

Error handling#

MoonBit uses checked errors: a function declares possible errors in its type, and callers must handle or propagate them. There are no implicit exceptions and no try prefix.

Defining and raising#

Example Description
suberror MyError Define an error type with no payload.
suberror MyError { NotFound(String); Denied } Errors with payloads: constructors can carry data.
pub(all) suberror E { ... } Export the error type so it can be constructed and matched outside the package.
raise MyError::Denied Raise an error; the function signature must declare raise MyError.
Error The general error type; any suberror is automatically promoted to it.
let e : Error = MyError::Denied Concrete errors are promoted automatically; when matching, use _ to catch other error types.
raise Failure("boom") Built-in error Failure(String); fail is usually preferred.
fail("message") Shorthand for raising Failure, includes the call site, returns any type (diverges).
abort("message") Terminate the process immediately without stack unwinding.
panic() Trigger a panic, no arguments; used for unrecoverable program errors.

Declaring and propagating#

Example Description
fn f() -> Int raise MyError { ... } Declare a concrete error type.
fn f() -> Int raise { ... } Omit the error type; equivalent to raise Error.
fn f() -> Int noraise { ... } Explicitly declare that nothing is raised; higher-order functions use this for error inference.
fn[T] poly(f : () -> T raise?) -> T raise? Error polymorphism: the argument decides whether it raises (generic parameters go after fn).
let x = f() Calling it inside a raise function propagates automatically, no try needed.
fn g() -> Int raise MyError { f() + 1 } The caller's signature must cover the callee's errors.
f() catch { _ => 0 } Catch in place and provide a default value.
f() catch { MyError::NotFound(k) => 0; _ => -1 } Branch on the error constructor.
pub suberror ParseError {
  Empty
  BadChar(Char)
}

fn parse_digit(c : Char) -> Int raise ParseError {
  if c >= '0' && c <= '9' {
    c.to_int() - '0'.to_int()
  } else {
    raise ParseError::BadChar(c)
  }
}

/// Errors propagate upward automatically: no need to write try.
fn parse_two(a : Char, b : Char) -> Int raise ParseError {
  parse_digit(a) * 10 + parse_digit(b)
}

Catching and converting#

Example Description
expr catch { pattern => handler } Catch an error raised by the expression.
try expr catch { e => ... } noraise { v => ... } Full form: handle failure and success separately.
try Ok(expr) catch { e => Err(e) } Turn a raise expression into a Result (replaces the removed try?).
try Some(expr) catch { _ => None } Convert to Option when you only care whether it succeeds.
Result[T, E] Pass errors as ordinary values; good for cross-layer APIs.
Ok(v) / Err(e) Construct a Result.
r.unwrap() Extract the Ok value; panics on Err.
r is Ok() / r is Err() Test the branch without taking the value.
match r { Ok(v) => ...; Err(e) => ... } Handle both branches explicitly.
match e { MyError::_ as x => ...; _ => ... } Match only one kind of suberror on an Error.
try! f() Panic on unexpected errors, for scenarios that cannot fail.
test "catch" {
  // Fall back in place
  inspect(parse_digit('7') catch { _ => -1 }, content="7")

  // Convert to Result
  let r : Result[Int, ParseError] = try Ok(parse_digit('x')) catch { e => Err(e) }
  inspect(r is Err(_), content="true")

  // Handle success and failure separately
  let doubled = parse_digit('4') catch { _ => 0 } noraise { v => v * 2 }
  inspect(doubled, content="8")
}

Which to use when#

Scenario Recommendation
Recoverable input errors, IO failures suberror + raise, or Result[T, E]
A library's public API needs explicit handling by callers Result[T, E] return value
Internal code, prototypes, scripts raise a generic error + catch { _ => 默认值 }
Assertion failure in tests fail("...") or assert_eq
Unrecoverable broken invariant panic() / abort()

> Note 错 — try? has been removed from the language 弃; rewrite it as try Ok(expr) catch { e => Err(e) }.

> Idiom 荐 — Define error types as suberror enums and put context (key names, positions, invalid characters) in the payload; callers can then branch precisely on the constructor instead of comparing strings.

Strings and characters#

String is an immutable UTF-16 sequence; StringView is its zero-copy slice. Indexing returns code units, so character-based operations need dedicated methods.

Literals and interpolation#

Example Description
"hello" String literal.
"line\nbreak" Escapes: \n, \t, \, &quot;, \u{1F600}.
"Hello, {name}!" Interpolation: {表达式} renders via Show.
"x = {x + 1}" Simple expressions are allowed in interpolation.
"{p}" 错 String literals and quotes cannot appear in interpolation; extract a variable first, then interpolate.
'a' / '\n' / '中' Character literal; Char is a Unicode scalar value.
b"abc" Byte-string literal, type Bytes.
#|第一行<br>#|第二行 Multiline string: each line starts with #|, preserving newlines.
test "interpolation" {
  let name = "MoonBit"
  let version = 1
  inspect("Hello, \{name} v\{version}", content="Hello, MoonBit v1")
}

Indexing and slicing#

Example Description
s.length() Number of code units (UTF-16).
s.char_length() Number of Unicode characters; an emoji counts as 1.
s.code_units() Get an ArrayView[UInt16].
s[i] Return the i-th code unit (UInt16); panics out of bounds.
s.get(i) Return UInt16?; out of bounds gives None.
s.get_char(i) Return Char?; indexed by code unit.
s.at(i) Same as s[i]; returns UInt16.
s[a:b] Slice to a StringView; bounds are clamped to valid positions.
s.get_view(start=, end=) Safe slice, returns StringView?.
s[:] Full view StringView, zero-copy.
v.to_owned() StringView → owned String.
s.to_string_view() String → StringView.

Searching and transforming#

Example Description
s.contains("Moon") Whether it contains the substring.
s.has_prefix("He") / s.has_suffix("!") Prefix / suffix test.
s.find("Moon") Position of the first occurrence, returns Int?.
s.split(",") Split by a delimiter, returns Iter[StringView].
s.split(",").collect() Collect into Array[StringView].
s.trim() Trim leading and trailing whitespace, returns StringView.
s.trim(chars="ab") Trim the given set of characters from both ends.
s.to_upper() / s.to_lower() Case conversion, returns a new String.
s.replace(old="a", new="b") Replace the first match.
s.replace_all(old="a", new="b") Replace all matches.
s.repeat(3) Repeat and concatenate.
s.pad_start(8, '0') / s.pad_end(8, ' ') Pad left / right to a given length.
s.rev() Reverse the character order.
s.is_empty() Whether it is an empty string.
s.escape() Escape into a form embeddable in source code.
s.to_array() Convert to Array[Char].
String::from_array(chars) Construct from ArrayView[Char].
String::from_iter(iter) Construct from a character iterator.
names.join(",") Join Array[String] into a string.
test "string ops" {
  let s = "  Hello, MoonBit  "
  let t = s.trim()
  inspect(t, content="Hello, MoonBit")
  inspect(t.to_upper(), content="HELLO, MOONBIT")
  inspect(t.replace(old="MoonBit", new="World"), content="Hello, World")
  inspect(t.has_prefix("Hello"), content="true")
  inspect(t[7:11], content="Moon")
  inspect(t.split(", ").collect().length(), content="2")
}

Building strings#

Example Description
StringBuilder() Create a builder; do not use the deprecated StringBuilder::new().
sb.write_string("abc") Append a string.
sb.write_char('x') Append a character.
sb.write_object(value) Append any value via Show.
sb.to_string() Get the result.
sb.reset() Clear it for reuse.
"a" + "b" For a few concatenations use + directly; in loops use StringBuilder.
test "builder" {
  let sb = StringBuilder()
  sb.write_string("count = ")
  sb.write_object(3)
  inspect(sb.to_string(), content="count = 3")
}

Parsing#

Example Description
@string.parse_int("42") Parse an Int; raises on failure.
@string.parse_int("ff", radix=16) Specify the radix.
@string.parse_double("3.5") Parse a Double.
@string.parse_bool("true") Parse a Bool.
@string.parse_int("42") catch { _ => 0 } Provide a default on parse failure.
@string.parse_int("42") catch { _ => 0 } noraise { v => v } Handle success and failure separately.
test "parse" {
  let n = @string.parse_int("42") catch { _ => 0 }
  inspect(n, content="42")
  let d = @string.parse_double("3.5") catch { _ => 0.0 }
  inspect(d, content="3.5")
}

> Note 错 — String's length() is the number of code units, not the number of visible characters. When truncating user input, use char_length() and get_view to avoid cutting an emoji in half a surrogate pair.

> Performance — Repeatedly doing s = s + piece in a loop allocates constantly; switch to StringBuilder, or collect the pieces into Array[String] first and then join.

Collections#

Array, FixedArray, and ArrayView are three array forms; Map and Set are hash containers; Iter is a lazy iterator.

Array#

Example Description
[1, 2, 3] Array literal; an empty array is written [] (needs a type annotation or context).
a.length() Number of elements.
a[i] / a[i] = v Index read and write; panics out of bounds.
a.get(i) Safe read, returns T?.
a.push(v) Append to the end.
a.pop() Pop from the end, returns T?.
a.insert(i, v) Insert at position i.
a.remove(i) Remove and return the element at position i.
a.contains(v) Whether it contains v (requires Eq).
a.search(v) Return the index as Int?.
a.sort() Sort in place ascending (requires Compare).
a.sort_by(fn(x, y) { y - x }) Custom comparator; the example sorts descending.
a.rev() Return a reversed new array.
a.rev_in_place() Reverse in place, returns Unit.
a.map(fn(x) { x * 2 }) Map to a new array.
a.filter(fn(x) { x > 0 }) Filter into a new array.
a.fold(init=0, fn(acc, x) { acc + x }) Fold to a single value.
a.each(fn(x) { ... }) Iterate and run side effects.
a[1:3] Slice to an ArrayView[T].
a[:] Full view, zero-copy.
a.is_empty() Whether it is empty.
names.join(",") Join Array[String].
test "array" {
  let a = [3, 1, 2]
  a.push(4)
  a.sort()
  inspect(a, content="[1, 2, 3, 4]")
  inspect(a.map(x => x * 2), content="[2, 4, 6, 8]")
  inspect(a.filter(x => x > 2), content="[3, 4]")
  inspect(a.fold(init=0, fn(acc, x) { acc + x }), content="10")
  inspect(a[1:3], content="[2, 3]")
}

> Semantics — Arrays are references: in-place modification after passing to a function affects the caller. When you need a copy, use a.copy() or a[:].to_array().

FixedArray and views#

Example Description
FixedArray::make(3, 0) Create a fixed-length array of length 3, all initialized to 0.
FixedArray::from_array([1, 2]) Copy-construct from an Array.
f[i] / f[i] = v Fixed-length arrays also support index read and write.
f.length() Length; unchanged after creation.
f[:] Convert to ArrayView[T].
v.to_array() Convert a view back to an owned Array.
a[1:3] Array slicing produces a view without copying.
test "fixed array" {
  let f : FixedArray[Int] = FixedArray::make(3, 0)
  f[0] = 7
  inspect(f[0], content="7")
  inspect(f[:].to_array(), content="[7, 0, 0]")
}

Map#

Example Description
{ "a": 1, "b": 2 } Map literal, type Map[String, Int].
Map([]) Empty Map; Map::new() is deprecated.
Map::from_iter([("a", 1)]) Construct from a key-value iterator.
m["a"] = 1 Insert or overwrite.
m["a"] Read; panics when the key is absent.
m.get("a") Safe read, returns V?.
m.get_or_default("a", 0) Return a default when missing.
m.get_or_init("a", fn() { 0 }) Call a function to generate and insert when missing.
m.contains("a") Whether the key exists.
m.remove("a") Remove the key.
m.remove_and_get("a") Remove and return the old value.
m.length() Number of key-value pairs.
m.keys() / m.values() Iterator over keys / values.
m.to_array() Convert to Array[(K, V)].
for k, v in m { ... } Iterate; order is undefined, so if you need stable order, extract the keys and sort first.
m.map(fn(k, v) { v + 1 }) Map over values, returns a new Map.
m.filter(fn(k, v) { v > 0 }) Filter, returns a new Map.
test "map" {
  let m : Map[String, Int] = { "a": 1, "b": 2 }
  m["c"] = 3
  inspect(m.get("a"), content="Some(1)")
  inspect(m.get_or_default("z", 0), content="0")
  inspect(m.length(), content="3")
  let mut total = 0
  for _k, v in m {
    total = total + v
  }
  inspect(total, content="6")
}

Set#

Example Description
@hashset.HashSet([]) Create an empty set; requires importing moonbitlang/core/hashset.
s.insert(v) Insert an element (duplicate inserts have no effect).
s.contains(v) Whether it contains v.
s.remove(v) Remove an element.
s.length() Number of elements.
@hashset.HashSet::from_iter(xs.iter()) Construct from an iterator.
test "set" {
  let s : @hashset.HashSet[Int] = @hashset.HashSet([])
  s.insert(1)
  s.insert(1)
  inspect(s.length(), content="1")
  inspect(s.contains(1), content="true")
}

Iter#

Example Description
xs.iter() Get an iterator from an array / Map / string.
.map(f) / .filter(p) Lazy transform, returns a new Iter.
.take(n) / .drop(n) Take the first n / skip the first n.
.concat(other) Concatenate two iterators.
.fold(init=, f) Consume the iterator and fold.
.each(f) Consume the iterator and run side effects.
.collect() Collect into an Array.
.count() Number of elements (consumes the iterator).

> Note 错 — Iter is single-use: after let it = xs.iter(); it.take(2).collect(); it.drop(2).collect(), the second call yields an empty result. For multiple traversals, collect() first or call iter() again each time.

Numbers and conversions#

MoonBit integer literals are overloaded by target type: the same 1 can be assigned to Int, Int64, Byte, or Double.

Types and literals#

Example Description
42 Decimal integer; the type is determined by context, defaulting to Int.
1_000_000 Underscore separators for readability.
0xFF / 0b1010 Hexadecimal / binary literal.
1.5 / 1.5e3 / 1.5e-3 Floating-point literal; defaults to Double.
let x : Int64 = 1 Explicitly annotate the target type.
let b : Byte = 3 Byte literal; b"abc" is a byte string.
'A' Character literal; 'A'.to_int() gives 65.
true / false Boolean literal.
Type Width Description
Int 32-bit signed Alias of Int32, the most common.
Int64 / UInt64 64-bit Large integers, timestamps.
UInt 32-bit unsigned Alias of UInt32.
Int16 / UInt16 16-bit Corresponds to a String code unit.
Byte 8-bit unsigned Byte buffers, binary protocols.
Double / Float 64 / 32-bit float The default float type is Double.

Operations#

Example Description
a + b / a - b / a * b / a / b / a % b Arithmetic; integer division truncates toward zero.
-7 / 2 == -3 Truncation, not floor.
-7 % 2 == -1 The remainder sign follows the dividend.
a & b / a | b / a ^ b Bitwise AND / OR / XOR.
a << n / a >> n Left shift / right shift.
a == b / a != b Equality comparison.
a < b / a <= b / a > b / a >= b Ordering comparison.
a && b / a || b / !a Logical AND / OR / NOT (short-circuit).

Conversions#

Example Description
i.to_int64() Int → Int64.
i.to_double() Integer → Double.
i.to_uint() Signed → unsigned (bitwise reinterpretation).
d.to_int() Double → Int, truncating the fractional part.
d.to_int64() Double → Int64.
b.to_int() Byte → Int.
f.to_double() Float → Double.
c.to_int() Char → Unicode code point.
Char::from_int(66) Code point → Char.
i.to_string() Convert to a string.
i.to_string(radix=16) Output in a given radix; note that literal calls need parentheses: (42).to_string(radix=16).
@string.parse_int("42") String → integer; raises on failure.
test "numbers" {
  inspect(1_000_000, content="1000000")
  inspect(0xFF, content="255")
  inspect(0b1010, content="10")
  inspect((42).to_string(radix=16), content="2a")
  inspect((-7) / 2, content="-3")
  inspect('A'.to_int(), content="65")
  inspect(Char::from_int(66), content="B")
}

Math#

Example Description
(-3).abs() or Int::abs(-3) Absolute value.
d.sqrt() Square root.
@math.pow(2.0, 10.0) Exponentiation; d.pow() is deprecated, use @math.pow.
d.floor() / d.ceil() / d.round() Round down / up, and round to nearest.
@math.trunc(d) Truncate the fractional part.
@math.sin(x) / @math.cos(x) / @math.tan(x) Trigonometric functions.
@math.ln(x) / @math.log2(x) / @math.log10(x) Logarithms.
@math.exp(x) Exponential function.
@math.hypot(x, y) Hypotenuse of a right triangle.
Float versions Most of the functions above have f-suffixed versions, such as @math.sinf, @math.cosf, @math.powf.
test "math" {
  inspect(9.0.sqrt(), content="3")
  inspect(@math.pow(2.0, 10.0), content="1024")
  inspect(3.7.floor(), content="3")
  inspect(3.7.ceil(), content="4")
  inspect(3.5.round(), content="4")
}

> Note 错 — Do not compare floats with a == b; use a difference threshold: (a - b).abs() < 1e-9. NaN is not equal to any value, including itself.

> Performance — Integer arithmetic defaults to 32 bits; for large-range counting (byte counts, timestamps), use Int64 / UInt64 explicitly to avoid debugging overflows after the fact.

JSON#

JSON support comes in two layers: #derive(ToJson, FromJson) for type-level serialization, and @json.Json for dynamic tree operations.

Type-level serialization#

Example Description
#derive(ToJson) Generate a serialization implementation for structs / enums.
#derive(FromJson) Generate a deserialization implementation.
#derive(ToJson, FromJson, Eq) Derive together for convenient round-trip tests.
@json.to_json(value) Any ToJson value → Json.
json.stringify() Json → compact string.
json.stringify(indent=2) Indented, pretty-printed output.
@json.parse(text) String → Json; raises ParseError on failure.
@json.from_json(json) Json → concrete type; raises JsonDecodeError on failure.
@json.valid(text) Whether it is valid JSON; returns Bool.
#derive(ToJson, FromJson, Debug, Eq)
pub(all) struct Package {
  name : String
  version : Int
}

test "roundtrip" {
  let p = Package::{ name: "cheats.mbt", version: 1 }
  let j = @json.to_json(p)
  inspect(j.stringify(), content="{\"name\":\"cheats.mbt\",\"version\":1}")
  let back : Package = @json.from_json(j)
  inspect(back == p, content="true")
}

Dynamic JSON tree#

Constructor Description
@json.Json::object(map) Object; the argument is Map[String, Json].
@json.Json::array(arr) Array; the argument is Array[Json].
@json.Json::string("x") String value.
@json.Json::number(1.0) Number value (internally a Double).
@json.Json::boolean(true) Boolean value.
@json.Json::null() Null value; Json::Null is a read-only constructor and cannot be created directly.
Accessor Description
j.value("key") Object field, returns Json?.
j.item(0) Array element, returns Json?.
j.as_string() Get the string; returns None on type mismatch.
j.as_number() Get the number (Double?).
j.as_bool() / j.as_null() Get the boolean / null.
j.as_array() Get the array, returns Array[Json]?.
j.as_object() Get the object, returns Map[String, Json]?.
match j { Json::Object(m) => ...; _ => ... } Pattern-match the seven constructors directly.
test "json tree" {
  let obj = @json.Json::object({
    "name": @json.Json::string("moon"),
    "stars": @json.Json::number(42.0),
  })
  inspect(obj.stringify(), content="{\"name\":\"moon\",\"stars\":42}")
  inspect(obj.value("name").is_empty(), content="false")
  inspect(obj.as_object().is_empty(), content="false")
}

Enum serialization styles#

Derive form Effect
#derive(ToJson(style="legacy")) {"$tag":"A","x":1}, keeps the tag field.
#derive(ToJson(style="flat")) ["A", 1], more compact.
#derive(FromJson(style="legacy")) Used paired with the matching style.
#derive(ToJson(fields(x(rename="X")))) Field renaming (coarse-grained control).

> Note — Derive parameters are only good for coarse adjustments; when you need precise control over field layout, write impl ToJson for T with to_json(self) { ... } by hand.

> Note 错 — Json's Number is stored as a Double, so integers beyond 2^53 lose precision; to preserve large integers exactly, parse with preserve_number_repr=true or encode them as strings.

Async#

async fn declares an async function; the call site needs no await—just write let v = f() to get the result.

Basics#

Example Description
async fn f() -> Int { 1 } Declare an async function; the return type is still Int.
let v = f() Call an async function; the result is Int directly, and the compiler awaits automatically.
@async.pause() Yield execution and wait for the next scheduling round.
async test "name" { ... } Async test, supported by moon test.
async fn f() -> Int raise E { ... } Async and error declarations can be combined.
f() catch { _ => 0 } Error handling for async calls is the same as for synchronous calls.
async fn fetch(n : Int) -> Int {
  @async.pause()
  n * 2
}

async test "async" {
  let v = fetch(3)
  inspect(v, content="6")
}

Concurrency combinators#

Example Description
@async.all([f1, f2]) Run all tasks concurrently, returning a result array in order.
@async.all(tasks, max_concurrency=4) Limit the maximum concurrency.
@async.any([f1, f2]) Return the result of the first to finish.
@async.any(tasks, allow_failure=true) Allow failing tasks to compete.
@async.now() Current timestamp (Int64).
@async.is_being_cancelled() Whether the current task has been cancelled.
@async.protect_from_cancel(f) Mask cancellation during execution.
@async.handle_cancellation(f) Turn cancellation into an Option: returns None when cancelled.
async test "concurrency" {
  let xs = @async.all([fn() { fetch(1) }, fn() { fetch(2) }])
  inspect(xs, content="[2, 4]")
}

Cancellation#

Example Description
@async.is_being_cancelled() Poll inside long tasks to exit voluntarily.
@async.handle_cancellation(f) Capture cancellation, returns X?.
@async.protect_from_cancel(f) Critical sections are not allowed to be cancelled.
@async.pause() Cancellation usually happens at yield points.

> Note — Cancellation is cooperative: a task that never checks is_being_cancelled() and never passes through pause() will not be interrupted.

> Idiom 荐 — Write concurrent tasks as fn() { ... } closures and pass them to @async.all; this is far simpler than maintaining a task queue by hand. Use max_concurrency when you need to throttle.

FFI and backends#

The same MoonBit code can compile to four backends; FFI declarations are per-backend and isolated by conditional compilation.

External functions#

Example Description
extern "C" fn f(x : Int) -> Int = "sym" Native backend: link the C symbol sym.
extern "js" fn f() -> Double = "() => Date.now()" JS backend: the body is written directly in JavaScript.
extern "wasm" fn f() -> Int = "env" "f" Wasm backend: import function f from module env; inline functions are written # (func ...) and have no function name.
#external type Handle External opaque type: externref for wasm, any for js, void* for native.
#borrow(params..) / #owned(params..) Ownership annotations for C FFI pointer parameters; params is a subset of parameter names and must appear before the extern declaration.
#export_name("name") Export symbol name; only valid for packages with pkgtype(kind: "foreign_library").
extern "js" fn now_ms() -> Double = "() => Date.now()"

test "js ffi" {
  inspect(now_ms() > 0.0, content="true")
}

Backends#

Target Output Typical use
wasm .wasm linear-memory module Browsers, edge functions, plugins.
wasm-gc Module using Wasm GC Smaller artifacts that cooperate directly with the host GC.
js JavaScript (ESM / CJS / IIFE) Node.js, front-end integration.
native Native executable CLIs, servers.
llvm Native code via LLVM Scenarios that need LLVM optimizations.
Command Description
moon build --target js Build for a specific backend.
moon check --target all Type-check all backends.
moon run --target js cmd/main Run with a specific backend.
moon test --target wasm-gc Run tests on a specific backend.

Conditional compilation#

Form Description
#cfg(target="js") Compile the declaration only for the JS backend.
#cfg(platform="windows") Compile only in Windows native builds.
#cfg(not(target="js")) Negation.
#cfg(all(target="native", platform="linux")) Satisfy multiple conditions at once.
#cfg(any(target="js", target="wasm")) Satisfy any one condition.
#cfg(false) Temporarily exclude a block of code (safer than commenting out).
#cfg(target="js")
extern "js" fn host_now() -> Double = "() => Date.now()"

#cfg(target="native")
extern "C" fn host_now() -> Double = "monotonic_now"

Package-level configuration#

Configuration Description
pkgtype(kind: "executable") Executable package; must provide fn main.
pkgtype(kind: "foreign_library") Library that exports symbols for external calls, paired with #export_name.
options(targets: { "a.mbt": ["js"] }) Filter source files by backend.
options(targets: { "b.mbt": ["not", "js"] }) Exclude a backend.
warnings = "-2-29" Disable specific warnings (e.g. unused variables, unused packages).
options(
  targets: {
    "platform_js.mbt": [ "js" ],
    "platform_native.mbt": [ "native" ],
    "platform_wasm.mbt": [ "wasm", "wasm-gc" ],
  },
)

> Note 错 — extern "C" fails to compile on the wasm / js backends, and extern "js" fails likewise on the native backend. Put FFI for different backends in separate files and isolate them with options(targets: ...) or #cfg.

> Note — After editing moon.pkg, rerun moon check; package configuration is not hot-reloaded.

Behind the scenes#

Understanding these three things explains most of MoonBit's behavior: multi-backend compilation, reference semantics + GC, and sugar expansion.

Compilation pipeline#

Stage Description
Source .mbt source files; directories form packages, and moon.mod forms a module.
Type checking moon check only checks without emitting code; it also generates .mbti interface files.
Monomorphization Generics are expanded by concrete type at compile time, with no runtime type-erasure overhead.
Backend codegen Generate wasm / wasm-gc / js / native artifacts per target.
Execution wasm runs with moonrun, js with Node/browsers, native directly.
Concept Counterpart
Module One moon.mod; the unit published to mooncakes.
Package One directory + moon.pkg; the visibility boundary.
Interface (.mbti) The package's public signature generated by moon info, used to review API changes quickly.

Memory model#

Fact Implication
Has a GC No manual freeing, and no lifetime annotations.
Reference semantics by default Arrays, Maps, and structs with mut fields refer to the same data after being passed into a function.
Immutable values may be copied by the optimizer Semantically they are still values; the compiler may choose when to copy.
Ref[T] Provides a cell for primitive types (Int, Double, etc.) that can be modified by reference.
No null Express absence with Option[T] / T?.
Strings are immutable Every "modification" returns a new String.
struct Counter {
  mut value : Int
}

fn bump(c : Counter) -> Unit {
  c.value = c.value + 1 // Modifies the caller's object
}

test "reference semantics" {
  let c = Counter::{ value: 0 }
  bump(c)
  inspect(c.value, content="1")
}
Goal How
Modify the caller's struct inside a function Declare the field mut and assign directly.
Modify the caller's integer inside a function Use a Ref[Int] parameter and read/write r.val.
Do not modify the caller inside a function Pass a copy: a.copy(), a[:].to_array(), or construct a new value.
Shared mutable state Ref[T] plus a closure, or a struct with mut fields.

Sugar reference#

Form Expands to
a + b Add::add(a, b)
-a Neg::neg(a)
a == b Eq::equal(a, b)
a < b Compare::compare(a, b) compared against 0
a[i] at(a, i)
a[i] = v set(a, i, v)
a[1:3] View slice (ArrayView / StringView)
for x in xs Calls xs.iter() and takes elements one by one
"{x}" Renders x into a string via Show
x |> f f(x)
p.area() Type::area(p)
S::{ x: 1 } Struct literal construction
if c { a } else { b } Ternary expression (returns a value)
test "name" { ... } Registers a test case

> Tip — When you hit a "type mismatch", first expand the sugar into explicit calls (for example, write a + b as Add::add(a, b)); the error message often becomes clear immediately.

Toolchain#

A single moon command covers creating, building, running, testing, formatting, docs, and publishing; there is no separate package manager or build script.

Common commands#

Command Description
moon new hello Create a module and generate a minimal runnable project.
moon check Type-check without emitting binaries; the fastest inner-loop feedback.
moon check --target all Check all backends.
moon build Build the current module.
moon build --target js --release Specify the backend and optimization mode.
moon run cmd/main Run an executable package.
moon test Run all tests.
moon test -u Update inspect snapshots.
moon test -p 包路径 Test only the specified package.
moon test path/to/file.mbt Run only the tests in the specified file.
moon test -i 3 Run only the 3rd test; used with a single file, and also supports a 0-2 range.
moon test -p 包名 Test only the specified package.
moon fmt Format code and migrate old syntax.
moon info Generate .mbti interface files and review API changes.
moon doc --serve Start a local docs server (default 127.0.0.1:3000).
moon add moonbitlang/x Add a dependency and write it to moon.mod.
moon remove moonbitlang/x Remove a dependency.
moon tree View the dependency tree.
moon clean Clean build artifacts.
moon bench Run benchmarks.
moon coverage analyze Analyze test coverage.
moon login / moon publish Log in and publish to mooncakes.io.
moon upgrade Upgrade the toolchain.

Project structure#

hello/
├── moon.mod              # Module metadata (name, version, dependencies)
├── moon.pkg              # Root package configuration
├── hello.mbt             # Root package source
├── hello_test.mbt        # Black-box tests: can only call the public API
├── hello_wbtest.mbt      # White-box tests: can access private members in the package
├── cmd/
│   └── main/
│       ├── moon.pkg      # pkgtype(kind: "executable")
│       └── main.mbt      # fn main { ... }
├── src/
│   ├── moon.pkg
│   └── lib.mbt
└── _build/               # Build artifacts (do not commit)
Rule Description
One directory = one package A directory is only recognized if it contains moon.pkg.
Package name = path Write 用户名/模块/子目录 in dependencies and call with @子目录名.函数().
*_test.mbt Black-box tests; can only see pub APIs.
*_wbtest.mbt White-box tests; can test private implementations.
File order is irrelevant File order within a package does not affect compilation.
///| separates top-level blocks The official recommendation is to separate top-level items with ///| so tools can process them block by block.

moon.mod#

name = "justjavac/hello"
version = "0.1.0"
readme = "README.md"
repository = "https://github.com/justjavac/hello"
license = "Apache-2.0"
keywords = [ "demo" ]
preferred_target = "js"
description = "示例模块"
Field Description
name Publish name, format 用户名/模块名.
version Semantic version.
preferred_target Default backend for moon run / moon test.
readme / repository / license Information shown on the publish page.
Dependencies Added with moon add; no need to write version numbers by hand.

moon.pkg#

import {
  "justjavac/hello/src" @src,
  "moonbitlang/core/env",
}

pkgtype(kind: "executable")
Configuration Description
import { "路径" @别名 } Import a package; when the alias is omitted, the last path segment is used.
import { ... } for "test" A dependency visible only to tests.
pkgtype(kind: "executable") Executable package.
pkgtype(kind: "foreign_library") Library that exports symbols.
options(targets: { ... }) Filter source files by backend.
warnings = "-2-29" Disable specific warnings.

Testing#

Form Description
test "name" { ... } Named test block.
test { ... } Anonymous test block.
inspect(value, content="期望值") Snapshot assertion; moon test -u updates it automatically.
inspect(value) Leave it empty first, then run -u to fill in the actual value.
@json.json_inspect(value, content={ ... }) Structured snapshot with more readable output.
assert_eq(a, b) Equality assertion; prints both sides on failure.
assert_true(cond) / assert_false(cond) Boolean assertion.
test "panic ..." { ... } Convention: a name starting with panic marks an expected crash.
try Ok(f()) catch { e => Err(e) } Test a function that may raise.
test "inspect" {
  let result = 1 + 1
  inspect(result, content="2")
  assert_eq(result, 2)
  assert_true(result > 1)
}

> Tip — Snapshot tests turn "changing behavior" into a visible diff: run moon test to see the failure, then moon test -u to accept the new values, and finally review the snapshot change in code review.

Docs and publishing#

Form / command Description
/// 文档注释 Generate API docs; code blocks inside are checked by moon test.
moon doc --serve Preview docs locally.
moon info Update .mbti and check whether the public API changed unexpectedly.
moon login Log in to a mooncakes.io account.
moon publish Publish the current version.
moon add 用户/包@0.1.0 Reference a specific version.

> Note 错 — Do not commit _build/ to the repository; build artifacts and interface files should all be regenerated by moon.

Coding guidelines#

This section is opinion, not specification: a set of habits that make code shorter, clearer, and faster.

Idioms#

Habit Why
Use expressions instead of return if/match/loops already have values, so the last line of the function body is the return value.
Use Option[T] instead of sentinel values -1, "", and null are all less explicit than None.
Use match for exhaustive branches The compiler forces coverage of all constructors, so new branches are not missed.
Use guard ... else for early exit Put the exceptional path first and keep the main flow flat.
Use suberror enums for error types Callers can branch on the constructor instead of matching error strings.
Use StringView when parsing s[a:b] and split do not copy, which suits large inputs.
Default public structs to pub, and use pub(all) only when external construction is needed Shrinks the API surface and prevents external code from bypassing invariants.
Add #derive(Debug, Eq) to types Debug output and comparison are almost always needed.
Use labeled arguments when there are many parameters The call site is readable: create_window(title="x", width=800).
One cohesive package per directory A package is the visibility boundary and the unit of compilation and caching.
// Recommended: expressions + guard + match
fn classify(x : Int) -> String {
  guard x >= 0 else { return "negative" }
  match x {
    0 => "zero"
    1..=9 => "digit"
    _ => "large"
  }
}

Performance#

Advice Description
Use StringBuilder for concatenation in loops s = s + piece allocates a new string every time.
Use ArrayView for large-array traversal a[:] and a[1:3] do not copy the underlying data.
Use FixedArray for fixed-length buffers Avoids dynamic growth and an extra capacity field.
Use Array when frequent indexed access is needed Map has hashing overhead and suits sparse keys.
Avoid unnecessary to_string String allocation is a common hotspot; do not build messages when the log level is off.
Use concrete types instead of generics on hot paths Generics are monomorphized and usually fine, but over-generalizing increases compiled output.
Add --release to release builds Disables debug checks and enables optimizations.
Quantify with moon bench Do not optimize on intuition; measure first, then change.

> Reminder — MoonBit arrays and Maps use reference semantics, and function signatures do not copy data; call copy() only when you actually need a copy, and do not defensively copy out of habit.

Common pitfalls#

Pitfall Correct approach
Counting "characters" with s.length() Use s.char_length(); length() counts UTF-16 code units.
Consuming the same Iter twice Iterators are single-use; for multiple traversals, collect() first.
Assuming arrays are copied when passed Arrays are references; in-function changes affect the caller.
Writing let mut at the top level Top-level bindings are immutable; use Ref or a struct field.
let Some(x) = opt For refutable destructuring use match / guard ... else / if ... is.
42.to_string() Integer literal method calls need parentheses: (42).to_string().
Ambiguous struct literal type Add a type annotation or write Type::{ ... }.
Using 0..<n outside for Ranges work directly in for .. in and list comprehensions; elsewhere, collect them into an array first.
Forgetting the mut field Fields are immutable by default; add mut at the declaration before modifying.
Using integer division as floating point 7 / 2 == 3; convert to Double first when you need a fraction.

Migrating from older versions#

Old form 弃 New form
try? expr try Ok(expr) catch { e => Err(e) }
derive(Show, Eq) #derive(Debug, Eq) (before the declaration)
fn f[T](x : T) fn[T] f(x : T)
Map::new() Map([])
Set::new() @hashset.HashSet([])
StringBuilder::new() StringBuilder()
s.starts_with(x) s.has_prefix(x)
s.ends_with(x) s.has_suffix(x)
s.substring(start=, end=) s[a:b]
m.size() m.length()
opt.is_some() opt is Some(_)
loop { ... } for state = init { ... } or while true { ... }
.to_string() on a view .to_owned()

> Recommendation — After upgrading the toolchain, run moon fmt first (it migrates some old syntax), then moon check, and replace items one by one following the deprecation warnings; moon explain --diagnostic <编号> shows the official explanation for each diagnostic.

Miscellaneous#

Resource URL
Website and downloads moonbitlang.com
Language docs docs.moonbitlang.com
Online playground tour.moonbitlang.com
Standard library API mooncakes.io/docs/moonbitlang/core
Package registry mooncakes.io
Blog and weekly moonbitlang.com/blog
Standard library source github.com/moonbitlang/core
Agent skills github.com/moonbitlang/skills

About this page#

Item Description
Content A cheat sheet for MoonBit syntax, the standard library, the toolchain, and idioms.
Verification Key code examples are compiled and verified with moon check / moon test in this repository's examples/.
Generator Built with Fus: tools/prepare.mbtx preprocesses the four locale sources under _chapters/, and Fus emits /, /zh-tw/, /en/, and /ja/.
Languages Simplified Chinese, Traditional Chinese, English, Japanese — switch in the top bar. Anchors stay identical across locales.
Content license CC BY-SA 4.0.
Code license Apache-2.0.
Toolchain moonc 1.0.0-rc1.

Printing and PDF#

Action Description
Click the PDF button in the top-right corner Opens the browser print dialog.
Keyboard shortcut <kbd>P</kbd> Same as above.
Choose "Save as PDF" as the destination Produces a single-column A4 print version with interactive controls removed.
Print styles Automatically hide navigation and buttons, shrink the font size, and avoid breaking table rows across pages.

> Tip — The print version uses a single-column A4 layout, suitable for archiving and offline reading; for a two-column booklet, adjust the scale and margins in the print dialog.

Contributing#

Method Description
Report errors Point out the section anchor + expected behavior + actual output.
Fix content Edit the source for that locale (_chapters/*.md for Simplified Chinese, _chapters/{zh-tw,en,ja}/ otherwise) and add a compilable example in examples/.
Add a section Create _chapters/NN-name.md starting with # Title {#anchor}; it enters the table of contents automatically. Add the same file name to the other three locale directories.
Local preview Run ./build.sh, then open public/index.html.