MoonBit 是面向雲與邊緣運算的端到端語言工具鏈,可編譯到 Wasm、Wasm GC、JavaScript 與 Native 四種後端。它把代數資料型別、模式匹配、trait、檢查式錯誤處理與 async 放進一套小巧的語法裡,並自帶建置系統、套件管理器、測試與文件工具。
本頁是一份單頁速查表:依主題羅列語法與標準函式庫用法,適合已經會寫程式、需要快速查找的人。語法以 moonc 1.0.0-rc1 為準,關鍵範例經本機編譯驗證。
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 # 建立模組
cd hello
moon run cmd/main # 執行
moon test # 跑測試
線上試用:T · 下載與 IDE 設定:M
- 運算式導向:
if、match、迴圈都會回傳值;函式主體最後一個運算式即回傳值。
- 預設參照語意:陣列、Map、含
mut 欄位的結構體以參照傳遞;原始型別用 Ref[T] 明確可變。
- 無生命週期標註:有 GC,沒有所有權系統,學習曲線比 Rust 平緩。
- 檢查式錯誤:函式用
raise E 宣告可能拋出的錯誤,編譯器強制呼叫端處理或繼續傳播。
- 多後端:同一模組可混合 native 與 wasm/js 套件,共用領域模型。
- 編譯快、體積小:官方基準強調編譯速度與 Wasm 產物體積。
| 符號 |
含義 |
| L |
連結到語言參考(docs.moonbitlang.com) |
| T |
連結到線上演練場(tour.moonbitlang.com) |
| A |
連結到標準函式庫 API(mooncakes.io) |
| P |
連結到 mooncakes 套件頁面 |
| G |
連結到教學 |
| D |
連結到工具鏈文件 |
| M |
連結到 MoonBit 官網 |
| 错 |
錯誤範例或常見陷阱 |
| 弃 |
已棄用,新程式碼不要使用 |
| 验 |
實驗性特性,可能變動 |
| 荐 |
推薦用法 |
| 1 |
註腳 |
- 程式碼區塊中的
... 表示省略的實作細節。
T? 是 Option[T] 的簡寫,T 可以是任意型別。
- 標註 验 的內容在不同版本間可能調整;升級工具鏈後請以
moon check 為準。
- 型別名稱預設
UpperCamel,值與函式預設 lower_snake,列舉建構子必須大寫開頭。
MoonBit 用 struct、enum、type 三個關鍵字定義全部具名型別;沒有 class、繼承與 null。
| 範例 |
說明 |
struct S { x : Int; y : String } |
定義結構體,欄位預設不可變。 |
struct S { mut x : Int } |
mut 欄位可在原值上修改;含 mut 欄位的結構體以參照傳遞。 |
struct P(Int, String) |
元組結構體,用 .0、.1 存取;適合做輕量包裝。 |
struct H((Int) -> Unit) |
單欄位 newtype,常用於給函式型別一個名稱。 |
struct S {} |
空結構體;用 S::{} 建構({} 會被解析為空 Map)。 |
pub struct S { x : Int } |
套件外可讀、可模式匹配,但不能建構。 |
pub(all) struct S { x : Int } |
套件外可讀且可建構;需要外部 S::{ x: 1 } 時用它。 |
enum E { A; B(Int); C(x~ : Int) } |
定義列舉(代數資料型別):無參數、位置參數、帶標籤參數三種建構子。 |
enum E[T] { Leaf(T); Node(E[T], E[T]) } |
泛型遞迴列舉,建構子必須大寫開頭。 |
#derive(Debug, Eq, Compare) |
在型別宣告之前衍生 trait 實作。 |
type UserId = Int |
型別別名,零執行階段開銷;與 Int 完全等價,不能當獨立型別用。 |
priv struct S |
明確私有(套件內可見);頂層宣告預設就是私有。 |
#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
}
| 範例 |
說明 |
let x = 1 |
不可變綁定;型別通常可推斷。 |
let mut y = 2<br>y = y + 1 |
可變綁定,只允許區域變數;全域與欄位需明確 mut。 |
let x : Int64 = 1 |
明確型別標註;整數字面量依目標型別多載。 |
let (a, b) = (1, 2) |
元組解構綁定。 |
let Some(x) = opt 错 |
不可失敗的模式不能直接綁定,請用 match 或 guard。 |
const PI : Double = 3.14159 |
編譯期常數,必須標註型別。 |
let greeting : String = "hi" |
頂層不可變全域值,一般需要型別標註。 |
let mut counter : Int = 0 错 |
頂層 let 不能 mut;需要可變狀態請用 Ref 或結構體欄位。 |
| 範例 |
說明 |
Point::{ x: 1, y: 2 } |
建構結構體;Type:: 前綴在型別已知時可省略。 |
{ x: 1, y: 2 } |
目標型別已知時的簡寫(函式參數、回傳值、標註過的 let)。 |
Point::{ ..p, y: 3 } |
結構體更新:複製 p 的其餘欄位,覆蓋 y。 |
p.x |
具名欄位存取。 |
p.0 |
元組結構體的位置欄位存取。 |
p.y = 3 |
僅當欄位宣告為 mut 且 p 可寫時合法。 |
Shape::Circle(radius=1.0) |
列舉建構子;帶標籤參數用 名字= 或 名字~。 |
Shape::Empty |
無參數建構子就是一個值。 |
(1, "a") |
元組;元素型別可不同。 |
() |
單位值,也是單位型別;函式無回傳值時回傳它。 |
[1, 2, 3] |
陣列字面量,型別 Array[Int]。 |
{ "a": 1, "b": 2 } |
Map 字面量,型別 Map[String, Int]。 |
Ref(0) |
可變儲存格;用 r.val 讀寫。 |
| 型別 |
說明 |
Int |
32 位元有號整數(Int32 的別名)。 |
Int64 / UInt64 |
64 位元整數。 |
UInt |
32 位元無號整數(UInt32)。 |
Int16 / UInt16 |
16 位元整數。 |
Byte |
8 位元無號位元組。 |
Double / Float |
64 位元 / 32 位元浮點數。 |
Bool |
true / false。 |
Char |
Unicode 純量值;字面量 'a'、'\n'、'中'。 |
String |
不可變 UTF-16 字串;s[i] 回傳 code unit(UInt16)。 |
StringView |
字串切片視圖,s[:] 取得,零複製。 |
Bytes / BytesView |
不可變位元組序列與視圖,字面量 b"abc"。 |
Array[T] |
可變長陣列,參照語意。 |
FixedArray[T] |
定長陣列,建立後長度不變。 |
ArrayView[T] |
陣列視圖,a[:] 或 a[1:3] 取得。 |
Map[K, V] |
雜湊表;走訪順序未定義,不要依賴插入順序。 |
Set[T] |
雜湊集合,來自 moonbitlang/core/hashset,寫作 @hashset.HashSet[T]。 |
Option[T] / T? |
Some(v) 或 None,取代 null。 |
Result[T, E] |
Ok(v) 或 Err(e),用於明確錯誤值。 |
Unit |
單位型別,值寫作 ()。 |
Ref[T] |
可變參照儲存格,用於讓原始型別可按參照修改。 |
> 注意 错 —— String 是 UTF-16,s.length() 數的是 code unit 而不是字元數;emoji 等增補平面字元佔兩個 code unit。要按字元計數用 s.char_length()。
函式是 MoonBit 的基本組織單位:頂層函式、方法、閉包共用同一套 fn 語法。
| 範例 |
說明 |
fn f(x : Int) -> Int { x + 1 } |
普通函式;最後一個運算式即回傳值。 |
fn f() -> Unit { } |
無回傳值;-> Unit 可省略。 |
fn main { } |
程式進入點,無參數、無回傳值。 |
pub fn f() -> Int { 1 } |
匯出到套件外;預設是 priv。 |
fn[T] id(x : T) -> T { x } |
泛型參數寫在 fn 之後,不是函式名稱之後。 |
fn[A, B] pair(a : A, b : B) -> (A, B) { (a, b) } |
多個型別參數。 |
fn[T : Show + Eq] f(x : T) -> Unit { } |
帶 trait 約束的泛型。 |
fn f(x~ : Int) -> Int { x } |
必填標籤參數,呼叫時必須寫 x=。 |
fn f(x? : Int = 0) -> Int { x } |
選填標籤參數,帶預設值。 |
fn f(x : Int, y? : Int = 1) -> Int { x + y } |
位置參數與標籤參數可混用,標籤參數在後。 |
fn f() -> Int raise MyError { ... } |
宣告可能拋出 MyError;錯誤自動向上傳播。 |
fn f() -> Int raise { ... } |
不關心具體錯誤型別時,只寫 raise。 |
async fn f() -> Int { ... } |
非同步函式;呼叫端無須 await,直接得到結果。 |
extern "C" fn f(x : Int) -> Int = "sym" |
外部函式宣告,見 FFI。 |
fn f() -> Int { return 1 } |
return 用於提前回傳;末尾運算式不必寫 return。 |
/// 計算階乘;`///` 註解會進入文件並參與測試。
pub fn factorial(n : Int) -> Int {
if n <= 1 {
1
} else {
n * factorial(n - 1)
}
}
> 頂層函式預設相互遞迴,無需前置宣告;區域 fn 也可以遞迴。
| 範例 |
說明 |
f(1, 2) |
位置參數呼叫。 |
f(x=1, y=2) |
標籤參數可按任意順序給出。 |
f(x~, y~) |
簡寫:x=x, y=y,同名變數直接傳入。 |
f(1) |
省略帶預設值的選填參數。 |
p.area() |
方法呼叫語法;等價於 Shape::area(p)。 |
Shape::area(p) |
明確限定呼叫,避免與同名方法混淆。 |
xs.map(fn(x) { x * 2 }) |
把閉包作為值傳入。 |
xs.map(double) |
具名函式同樣是一等值。 |
expr |> f |
管線:把左側結果作為右側函式的第一個參數。 |
expr |> x => { x + 1 } |
管線配合匿名函式;x => expr 是閉包的簡寫。 |
| 範例 |
說明 |
fn Type::method(self : Type) -> Int { ... } |
為型別加入固有方法,可用 value.method() 呼叫。 |
fn Type::new(x : Int) -> Type { ... } |
關聯函式(無 self),用 Type::new(1) 呼叫。 |
impl Trait for Type with method(self) { ... } |
實作 trait 的一個方法;多個方法要寫多個 impl 區塊。 |
pub impl Trait for Type with method(self) { ... } |
匯出 trait 實作,套件外泛型程式碼才能用。 |
pub extend Type with Trait::{method} |
把 trait 方法提升為方法呼叫語法(value.method())。 |
impl Add for Vec with add(self, other) { ... } |
運算子多載,見 泛型與 trait。 |
pub(all) struct Rect {
width : Double
height : Double
}
/// 固有方法:第一個參數是 self。
pub fn Rect::area(self : Rect) -> Double {
self.width * self.height
}
/// 關聯函式:沒有 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")
}
| 範例 |
說明 |
fn(x) { x * 2 } |
匿名函式;參數型別可推斷。 |
fn(x : Int) -> Int { x * 2 } |
完整標註的匿名函式。 |
x => x * 2 |
單運算式簡寫,常用於 |> 與高階函式。 |
let f = fn(x) { x + 1 } |
閉包是值,可綁定、傳參、回傳。 |
fn() { counter.val = counter.val + 1 } |
閉包擷取外層變數;被擷取的可變狀態用 Ref。 |
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]")
}
| 範例 |
說明 |
test "name" { ... } |
測試區塊,moon test 收集並執行。 |
test { ... } |
匿名測試區塊,名稱自動產生。 |
async test "name" { ... } |
非同步測試。 |
fn main { ... } |
可執行套件進入點,配合 pkgtype(kind: "executable")。 |
bench "name" { ... } |
基準測試區塊,用 moon bench 執行。 |
extern "js" fn f() -> Int = "() => 1" |
JS 後端 FFI,函式主體是 JavaScript 原始碼。 |
extern "C" fn f(x : Int) -> Int = "c_symbol" |
Native 後端 FFI。 |
> 陷阱 错 —— 頂層函式預設相互遞迴,但區域函式之間的相互遞迴需要先宣告;遇到「未綁定識別字」時把其中一個改成頂層函式即可。
if、match、迴圈全部是運算式,可以出現在賦值右側或作為函式回傳值。
| 範例 |
說明 |
if x > 0 { "正" } else { "非正" } |
if 運算式回傳兩個分支的共同型別。 |
if a { 1 } else if b { 2 } else { 3 } |
else if 鏈。 |
if cond { do_something() } |
無 else 時回傳 Unit,只能當敘述用。 |
let x = if cond { 1 } else { 2 } |
把條件運算式賦值給變數。 |
guard x > 0 else { return } |
守衛:條件不成立時執行 else 區塊;可給替代值,也可用 return/raise 發散。 |
guard opt is Some(v) else { fail("空值") } |
守衛 + 模式匹配,成功後就地綁定 v。 |
fn sign(x : Int) -> String {
if x > 0 {
"positive"
} else if x < 0 {
"negative"
} else {
"zero"
}
}
| 範例 |
說明 |
match x { 0 => "零"; _ => "非零" } |
基本匹配;分支用換行或 ; 分隔。 |
match opt { Some(v) => v; None => 0 } |
解構 Option。 |
match e { Circle(r) => ...; Rect(w, h) => ... } |
解構列舉建構子。 |
match p { { x, y } => x + y } |
解構結構體欄位。 |
match xs { [] => 0; [x, .. rest] => x } |
陣列模式;.. rest 綁定剩餘部分。 |
match c { 'a'..='z' => 1; _ => 0 } |
區間模式。 |
match x { A | B => 1; _ => 0 } |
或模式,多個模式共用分支。 |
Some(x) if x > 0 => x |
分支守衛,寫在 => 之前。 |
match t { (a, b) => a + b } |
元組解構。 |
match s { "yes" => true; _ => false } |
字串字面量模式。 |
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
}
}
| 範例 |
說明 |
for x in xs { ... } |
走訪陣列、Map、字串、迭代器。 |
for i, x in xs { ... } |
同時取得索引與元素。 |
for i in 0..<n { ... } |
左閉右開區間;可用於 for .. in 與清單推導。 |
for i in 0..<=n { ... } |
遞增閉區間(編譯器也接受 0..=n)。 |
for i in n>..0 { ... } |
遞減:不含起點,含終點。 |
for i in n>=..0 { ... } |
遞減:含起點與終點。 |
[ for x in xs => x * x ] |
清單推導;=> 前可加 if 過濾。 |
for k, v in map { ... } |
走訪 Map 的鍵值對;順序未定義。 |
while cond { ... } |
條件迴圈。 |
while cond { ... } nobreak { ... } |
nobreak 區塊在迴圈正常結束(未觸發 break)時執行。 |
for i = 0 { ... continue i + 1 ... break i } |
函式式迴圈:明確攜帶狀態,break 帶出結果。 |
for i = 0; i < n; i = i + 1 { ... } |
C 風格頭部;可用 , 攜帶多個狀態。 |
for i = 0, sum = 0; i <= n; i = i + 1, sum = sum + i { } nobreak { sum } |
多狀態 + 迴圈正常結束時的取值。 |
break / continue |
跳出 / 繼續目前迴圈;break value 讓迴圈運算式回傳 value。 |
outer~: for x in xs { ... break outer~ v } |
標籤迴圈,可跨巢狀層跳出或繼續。 |
test "loops" {
// 區間迴圈
let mut sum = 0
for i in 0..<10 {
sum = sum + i
}
inspect(sum, content="45")
// 帶索引走訪
let names = ["a", "b"]
let mut out = ""
for i, name in names {
out = out + "\{i}:\{name};"
}
inspect(out, content="0:a;1:b;")
// 函式式迴圈:把狀態寫進迴圈頭
let total = for i = 0, acc = 0 {
if i < 5 {
continue i + 1, acc + i
} else {
break acc
}
}
inspect(total, content="10")
}
> 注意 —— loop { ... } 這種無狀態的函式式迴圈已棄用 弃;需要無限迴圈時寫 while true { ... },需要狀態時寫 for state = init { ... }。
| 範例 |
說明 |
return |
從函式回傳 Unit。 |
return value |
提前回傳一個值。 |
raise MyError::Bad |
拋出錯誤,型別上等價於發散。 |
fail("message") |
拋出通用 Failure,常用於測試與原型。 |
abort("message") |
立即終止程式,回傳任意型別(Never)。 |
panic() |
觸發 panic,無參數;測試中把案例命名為 test "panic ..." 表示預期崩潰。 |
defer cleanup() |
離開作用域時執行,包括錯誤、return、break、continue;多個 defer 逆序執行。 |
errdefer cleanup() |
僅當作用域拋錯或 async 被取消時執行。 |
> 慣用法 荐 —— 能用運算式就不用 return:if/match/迴圈的結果直接作為函式回傳值,程式碼更短且不易漏分支。
模式出現在 match 分支、guard、let 解構與 is 運算式中。編譯器檢查窮盡性:漏掉分支會直接報錯。
| 模式 |
說明 |
_ |
萬用字元,匹配任何值且不綁定。 |
x |
變數模式,綁定整個值(小寫開頭)。 |
42 / "ok" / 'a' / true |
字面量模式。 |
Some(x) / None |
Option 建構子模式。 |
Ok(v) / Err(e) |
Result 建構子模式。 |
Circle(radius~) |
列舉建構子 + 標籤欄位解構。 |
Circle(radius=r) |
同上,明確寫出欄位名稱。 |
Rect(w, h) |
位置參數建構子解構。 |
Empty |
無參數建構子模式。 |
{ x, y } |
結構體欄位解構,欄位名稱即綁定名稱。 |
{ x, .. } |
只取部分欄位,其餘忽略。 |
(a, b) |
元組解構。 |
[] / [x] / [x, .. rest] |
陣列模式;.. rest 綁定剩餘切片(ArrayView)。 |
[first, .. _middle, last] |
同時取首尾,中間忽略。 |
A | B |
或模式,多個模式共用一個分支。 |
'a'..='z' |
區間模式(字元、整數)。 |
pat if cond |
分支守衛:先匹配再判斷條件。 |
x is Some(_) |
is 運算式,回傳 Bool,可直接用於 if/guard。 |
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"
}
}
| 寫法 |
說明 |
let (a, b) = (1, 2) |
元組解構,必須窮盡。 |
guard p is { x, y } else { return } |
結構體解構 + 守衛,失敗時提前離開。 |
guard xs is [first, .. rest] else { ... } |
陣列解構 + 守衛。 |
if opt is Some(v) { use(v) } |
is 在 if 中綁定 v。 |
if r is Err(e) { log(e) } |
檢查 Result 分支。 |
match e { Circle(radius~) => radius; _ => 0.0 } |
只關心一個欄位時直接用標籤綁定。 |
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")
}
}
> 注意 错 —— let Some(x) = opt 不是合法綁定:let 只接受不可失敗的模式。可失敗的解構請用 match、guard ... else 或 if ... is。
> 慣用法 荐 —— 優先使用 match 而不是巢狀 if;把「建構子 + 守衛」寫在同一行,讀者能一次看清所有分支條件。
MoonBit 的抽象機制只有兩個:泛型(編譯期單態化)與 trait(行為約束)。沒有繼承,也沒有虛擬表語法。
| 範例 |
說明 |
fn[T] id(x : T) -> T { x } |
型別參數寫在 fn 之後。 |
fn[A, B] pair(a : A, b : B) -> (A, B) { (a, b) } |
多個型別參數。 |
fn[T : Show] f(x : T) -> String { x.to_string() } |
用 trait 約束型別參數,+ 連接多個約束。 |
struct Box[T] { value : T } |
泛型結構體。 |
enum Tree[T] { Leaf(T); Node(Tree[T], Tree[T]) } |
泛型遞迴列舉。 |
pub impl[T] Size for Box[T] with size(self) { ... } |
泛型 trait 實作;impl 後的 [T] 宣告型別參數。 |
#derive(Debug) |
衍生實作會為欄位自動加上同樣的約束。 |
| 範例 |
說明 |
trait T { method(Self) -> Int } |
定義 trait;方法簽章不寫 fn</strong>,Self 指實作型別。 |
pub trait T { ... } |
匯出 trait;預設只能在目前套件實作。 |
pub(open) trait T { ... } |
允許套件外型別實作該 trait。 |
trait T { f(Self) -> Int; g(Self) -> String } |
一個 trait 可宣告多個方法。 |
impl T for S with f(self) { ... } |
實作一個方法;多個方法寫多個 impl 區塊。 |
pub impl T for S with f(self) { ... } |
匯出實作,套件外泛型程式碼才能使用。 |
pub extend S with T::{f} |
把 trait 方法提升為 s.f() 方法呼叫語法。 |
T::f(value) |
明確限定呼叫,泛型上下文中常用。 |
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")
}
| 語法 |
trait 與方法 |
範例 |
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 等 |
Compare::compare |
p < q |
a & b / a | b / a ^ b |
BitAnd::land / BitOr::lor / BitXOr::lxor |
位元運算 |
a << n / a >> n |
Shl::shl / Shr::shr |
移位 |
a[i] |
at |
索引讀取 |
a[i] = v |
set |
索引寫入 |
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")
}
| 衍生 |
產生內容 |
#derive(Debug) |
結構化除錯輸出,配合 @debug.to_string 與 debug_inspect。 |
#derive(Eq) |
== / !=,逐欄位比較。 |
#derive(Compare) |
<、<=、>、>=;列舉依宣告順序比較。 |
#derive(Hash) |
可用於 Map / Set 的鍵。 |
#derive(Default) |
Default::default();列舉要求恰好一個無參數建構子。 |
#derive(ToJson) |
序列化為 JSON,配合 @json.to_json。 |
#derive(FromJson) |
從 JSON 反序列化,配合 @json.from_json。 |
#derive(Arbitrary) |
產生隨機值,用於屬性測試。 |
#derive(Debug, Eq, Compare, Hash, Default)
pub(all) struct Config {
host : String
port : Int
}
/// 衍生只產生實作;要讓方法可用,需明確提升。
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 }")
}
> 注意 错 —— derive(...) 寫在型別之後的舊語法已棄用 弃;請把 #derive(...) 放在宣告之前。#derive(Show) 同樣棄用,除錯請用 Debug。
> 注意 错 —— 衍生的 trait 方法不會自動出現在方法呼叫裡;需要 pub extend Type with Trait::{method} 才能在套件外使用 value.method()。
MoonBit 用檢查式錯誤:函式在型別裡宣告可能拋出的錯誤,呼叫端必須處理或繼續傳播。沒有隱式例外,也沒有 try 前綴。
| 範例 |
說明 |
suberror MyError |
定義無載荷錯誤型別。 |
suberror MyError { NotFound(String); Denied } |
帶載荷的錯誤:建構子可攜帶資料。 |
pub(all) suberror E { ... } |
匯出錯誤型別,套件外可建構與匹配。 |
raise MyError::Denied |
拋出錯誤;函式簽章必須宣告 raise MyError。 |
Error |
通用錯誤型別;任何 suberror 都會自動提升到它。 |
let e : Error = MyError::Denied |
具體錯誤自動提升;匹配時需用 _ 兜底其他錯誤型別。 |
raise Failure("boom") |
內建錯誤 Failure(String);實務上更推薦 fail。 |
fail("message") |
拋出 Failure 的簡寫,帶呼叫位置,回傳任意型別(發散)。 |
abort("message") |
立即終止行程,不做堆疊展開。 |
panic() |
觸發 panic,無參數;用於不可復原的程式錯誤。 |
| 範例 |
說明 |
fn f() -> Int raise MyError { ... } |
宣告具體錯誤型別。 |
fn f() -> Int raise { ... } |
省略錯誤型別,等價於 raise Error。 |
fn f() -> Int noraise { ... } |
明確宣告不拋錯;高階函式據此做錯誤推斷。 |
fn[T] poly(f : () -> T raise?) -> T raise? |
錯誤多型:由實參決定拋或不拋(泛型參數寫在 fn 後)。 |
let x = f() |
在 raise 函式中呼叫會自動向上傳播,無須 try</strong>。 |
fn g() -> Int raise MyError { f() + 1 } |
呼叫端簽章必須涵蓋被呼叫端的錯誤。 |
f() catch { _ => 0 } |
就地擷取並給出預設值。 |
f() catch { MyError::NotFound(k) => 0; _ => -1 } |
依錯誤建構子分支處理。 |
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)
}
}
/// 錯誤自動向上傳播:不需要寫 try。
fn parse_two(a : Char, b : Char) -> Int raise ParseError {
parse_digit(a) * 10 + parse_digit(b)
}
| 範例 |
說明 |
expr catch { pattern => handler } |
擷取運算式拋出的錯誤。 |
try expr catch { e => ... } noraise { v => ... } |
完整形式:分別處理失敗與成功。 |
try Ok(expr) catch { e => Err(e) } |
把 raise 運算式轉成 Result(取代已移除的 try?)。 |
try Some(expr) catch { _ => None } |
只關心成功與否時轉成 Option。 |
Result[T, E] |
把錯誤當普通值傳遞,適合跨層 API。 |
Ok(v) / Err(e) |
建構 Result。 |
r.unwrap() |
取出 Ok 值;Err 時 panic。 |
r is Ok() / r is Err() |
判斷分支,不取值。 |
match r { Ok(v) => ...; Err(e) => ... } |
明確處理兩個分支。 |
match e { MyError::_ as x => ...; _ => ... } |
在 Error 上只匹配某一種 suberror。 |
try! f() |
意外錯誤直接 panic,用於斷言不可能失敗的場景。 |
test "catch" {
// 就地兜底
inspect(parse_digit('7') catch { _ => -1 }, content="7")
// 轉成 Result
let r : Result[Int, ParseError] = try Ok(parse_digit('x')) catch { e => Err(e) }
inspect(r is Err(_), content="true")
// 成功與失敗分別處理
let doubled = parse_digit('4') catch { _ => 0 } noraise { v => v * 2 }
inspect(doubled, content="8")
}
| 場景 |
推薦 |
| 可復原的輸入錯誤、IO 失敗 |
suberror + raise,或 Result[T, E] |
| 函式庫的公開 API 需要呼叫端明確處理 |
Result[T, E] 回傳值 |
| 內部實作、原型、指令碼 |
raise 泛型錯誤 + catch { _ => 默认值 } |
| 測試中的斷言失敗 |
fail("...") 或 assert_eq |
| 不可復原的不變量破壞 |
panic() / abort() |
> 注意 错 —— try? 已從語言中移除 弃;請改寫為 try Ok(expr) catch { e => Err(e) }。
> 慣用法 荐 —— 錯誤型別用 suberror 定義成列舉,把上下文(鍵名、位置、非法字元)放進載荷;呼叫端就能依建構子精確分支,而不是比較字串。
String 是不可變 UTF-16 序列;StringView 是它的零複製切片。索引回傳 code unit,按字元操作要用專門的方法。
| 範例 |
說明 |
"hello" |
字串字面量。 |
"line\nbreak" |
轉義:\n、\t、\、"、\u{1F600}。 |
"Hello, {name}!" |
插值:{表达式} 呼叫 Show 算繪。 |
"x = {x + 1}" |
插值裡可寫簡單運算式。 |
"{p}" 错 |
插值中不能出現字串字面量與引號,先取出變數再插值。 |
'a' / '\n' / '中' |
字元字面量;Char 是 Unicode 純量值。 |
b"abc" |
位元組字串字面量,型別 Bytes。 |
#|第一行<br>#|第二行 |
多行字串:每行以 #| 開頭,保留換行。 |
test "interpolation" {
let name = "MoonBit"
let version = 1
inspect("Hello, \{name} v\{version}", content="Hello, MoonBit v1")
}
| 範例 |
說明 |
s.length() |
code unit 數量(UTF-16)。 |
s.char_length() |
Unicode 字元數量;emoji 計為 1。 |
s.code_units() |
取得 ArrayView[UInt16]。 |
s[i] |
回傳第 i 個 code unit(UInt16),越界 panic。 |
s.get(i) |
回傳 UInt16?,越界為 None。 |
s.get_char(i) |
回傳 Char?;按 code unit 定位。 |
s.at(i) |
與 s[i] 相同,回傳 UInt16。 |
s[a:b] |
切片,得到 StringView;邊界會被調整到合法位置。 |
s.get_view(start=, end=) |
安全切片,回傳 StringView?。 |
s[:] |
整體視圖 StringView,零複製。 |
v.to_owned() |
StringView → 獨立 String。 |
s.to_string_view() |
String → StringView。 |
| 範例 |
說明 |
s.contains("Moon") |
是否包含子字串。 |
s.has_prefix("He") / s.has_suffix("!") |
前綴 / 後綴判斷。 |
s.find("Moon") |
首次出現位置,回傳 Int?。 |
s.split(",") |
依分隔符切分,回傳 Iter[StringView]。 |
s.split(",").collect() |
收集成 Array[StringView]。 |
s.trim() |
去掉首尾空白,回傳 StringView。 |
s.trim(chars="ab") |
去掉首尾指定字元集合。 |
s.to_upper() / s.to_lower() |
大小寫轉換,回傳新 String。 |
s.replace(old="a", new="b") |
替換首個匹配。 |
s.replace_all(old="a", new="b") |
替換全部匹配。 |
s.repeat(3) |
重複串接。 |
s.pad_start(8, '0') / s.pad_end(8, ' ') |
左 / 右填充到指定長度。 |
s.rev() |
反轉字元順序。 |
s.is_empty() |
是否為空字串。 |
s.escape() |
轉義為可嵌入原始碼的形式。 |
s.to_array() |
轉成 Array[Char]。 |
String::from_array(chars) |
從 ArrayView[Char] 建構。 |
String::from_iter(iter) |
從字元迭代器建構。 |
names.join(",") |
Array[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")
}
| 範例 |
說明 |
StringBuilder() |
建立建構器;不要用已棄用的 StringBuilder::new()。 |
sb.write_string("abc") |
追加字串。 |
sb.write_char('x') |
追加字元。 |
sb.write_object(value) |
用 Show 追加任意值。 |
sb.to_string() |
取出結果。 |
sb.reset() |
清空,可重複使用。 |
"a" + "b" |
少量串接可直接用 +;迴圈中請用 StringBuilder。 |
test "builder" {
let sb = StringBuilder()
sb.write_string("count = ")
sb.write_object(3)
inspect(sb.to_string(), content="count = 3")
}
| 範例 |
說明 |
@string.parse_int("42") |
解析 Int,失敗時 raise。 |
@string.parse_int("ff", radix=16) |
指定進位。 |
@string.parse_double("3.5") |
解析 Double。 |
@string.parse_bool("true") |
解析 Bool。 |
@string.parse_int("42") catch { _ => 0 } |
解析失敗給預設值。 |
@string.parse_int("42") catch { _ => 0 } noraise { v => v } |
分別處理成功與失敗。 |
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")
}
> 注意 错 —— String 的 length() 是 code unit 數,不是肉眼看到的字元數。截斷使用者輸入時用 char_length() 與 get_view,避免把 emoji 切成半個代理對。
> 效能 —— 迴圈裡反覆 s = s + piece 會不斷配置;改用 StringBuilder,或先把片段收集到 Array[String] 再 join。
Array、FixedArray、ArrayView 是三種陣列形態;Map 與 Set 是雜湊容器;Iter 是惰性迭代器。
| 範例 |
說明 |
[1, 2, 3] |
陣列字面量;空陣列寫作 [](需要型別標註或上下文)。 |
a.length() |
元素個數。 |
a[i] / a[i] = v |
索引讀寫;越界 panic。 |
a.get(i) |
安全讀取,回傳 T?。 |
a.push(v) |
尾部追加。 |
a.pop() |
彈出尾部,回傳 T?。 |
a.insert(i, v) |
在位置 i 插入。 |
a.remove(i) |
刪除並回傳位置 i 的元素。 |
a.contains(v) |
是否包含(需要 Eq)。 |
a.search(v) |
回傳索引 Int?。 |
a.sort() |
原地遞增排序(需要 Compare)。 |
a.sort_by(fn(x, y) { y - x }) |
自訂比較器,範例為遞減。 |
a.rev() |
回傳反轉後的新陣列。 |
a.rev_in_place() |
原地反轉,回傳 Unit。 |
a.map(fn(x) { x * 2 }) |
映射為新陣列。 |
a.filter(fn(x) { x > 0 }) |
過濾為新陣列。 |
a.fold(init=0, fn(acc, x) { acc + x }) |
摺疊為單值。 |
a.each(fn(x) { ... }) |
走訪並執行副作用。 |
a[1:3] |
切片,得到 ArrayView[T]。 |
a[:] |
整體視圖,零複製。 |
a.is_empty() |
是否為空。 |
names.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]")
}
> 語意 —— 陣列是參照:傳入函式後原地修改會影響呼叫端。需要副本時用 a.copy() 或 a[:].to_array()。
| 範例 |
說明 |
FixedArray::make(3, 0) |
建立長度 3、初值全為 0 的定長陣列。 |
FixedArray::from_array([1, 2]) |
從 Array 複製建構。 |
f[i] / f[i] = v |
定長陣列同樣支援索引讀寫。 |
f.length() |
長度,建立後不變。 |
f[:] |
轉為 ArrayView[T]。 |
v.to_array() |
視圖轉回獨立 Array。 |
a[1:3] |
陣列切片產生視圖,不複製。 |
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]")
}
| 範例 |
說明 |
{ "a": 1, "b": 2 } |
Map 字面量,型別 Map[String, Int]。 |
Map([]) |
空 Map;Map::new() 已棄用。 |
Map::from_iter([("a", 1)]) |
從鍵值對迭代器建構。 |
m["a"] = 1 |
插入或覆蓋。 |
m["a"] |
讀取;鍵不存在時 panic。 |
m.get("a") |
安全讀取,回傳 V?。 |
m.get_or_default("a", 0) |
缺失時回傳預設值。 |
m.get_or_init("a", fn() { 0 }) |
缺失時呼叫函式產生並插入。 |
m.contains("a") |
鍵是否存在。 |
m.remove("a") |
刪除鍵。 |
m.remove_and_get("a") |
刪除並回傳舊值。 |
m.length() |
鍵值對數量。 |
m.keys() / m.values() |
鍵 / 值的迭代器。 |
m.to_array() |
轉為 Array[(K, V)]。 |
for k, v in m { ... } |
走訪;順序未定義,需要穩定順序就先取出鍵排序。 |
m.map(fn(k, v) { v + 1 }) |
對值映射,回傳新 Map。 |
m.filter(fn(k, v) { v > 0 }) |
過濾,回傳新 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")
}
| 範例 |
說明 |
@hashset.HashSet([]) |
建立空集合;需要匯入 moonbitlang/core/hashset。 |
s.insert(v) |
插入元素(重複插入無效果)。 |
s.contains(v) |
是否包含。 |
s.remove(v) |
刪除元素。 |
s.length() |
元素個數。 |
@hashset.HashSet::from_iter(xs.iter()) |
從迭代器建構。 |
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")
}
| 範例 |
說明 |
xs.iter() |
從陣列 / Map / 字串取得迭代器。 |
.map(f) / .filter(p) |
惰性變換,回傳新的 Iter。 |
.take(n) / .drop(n) |
取前 n 個 / 跳過前 n 個。 |
.concat(other) |
串接兩個迭代器。 |
.fold(init=, f) |
消費迭代器並摺疊。 |
.each(f) |
消費迭代器並執行副作用。 |
.collect() |
收集為 Array。 |
.count() |
元素個數(消費迭代器)。 |
> 注意 错 —— Iter 是一次性的:let it = xs.iter(); it.take(2).collect(); it.drop(2).collect() 第二次會得到空結果。需要多次走訪時先 collect(),或每次重新 iter()。
MoonBit 的整數字面量依目標型別多載:同一個 1 可以賦給 Int、Int64、Byte、Double。
| 範例 |
說明 |
42 |
十進位整數;型別由上下文決定,預設 Int。 |
1_000_000 |
底線分隔,提升可讀性。 |
0xFF / 0b1010 |
十六進位 / 二進位字面量。 |
1.5 / 1.5e3 / 1.5e-3 |
浮點字面量;預設 Double。 |
let x : Int64 = 1 |
明確標註目標型別。 |
let b : Byte = 3 |
位元組字面量;b"abc" 是位元組字串。 |
'A' |
字元字面量;'A'.to_int() 得 65。 |
true / false |
布林字面量。 |
| 型別 |
寬度 |
說明 |
Int |
32 位元有號 |
Int32 的別名,最常用。 |
Int64 / UInt64 |
64 位元 |
大整數、時間戳記。 |
UInt |
32 位元無號 |
UInt32 的別名。 |
Int16 / UInt16 |
16 位元 |
與 String 的 code unit 對應。 |
Byte |
8 位元無號 |
位元組緩衝區、二進位協定。 |
Double / Float |
64 / 32 位元浮點 |
預設浮點型別是 Double。 |
| 範例 |
說明 |
a + b / a - b / a * b / a / b / a % b |
算術運算;整數除法向零截斷。 |
-7 / 2 == -3 |
截斷而非向下取整。 |
-7 % 2 == -1 |
餘數符號跟隨被除數。 |
a & b / a | b / a ^ b |
位元且 / 或 / 互斥或。 |
a << n / a >> n |
左移 / 右移。 |
a == b / a != b |
相等比較。 |
a < b / a <= b / a > b / a >= b |
大小比較。 |
a && b / a || b / !a |
邏輯且 / 或 / 非(短路)。 |
| 範例 |
說明 |
i.to_int64() |
Int → Int64。 |
i.to_double() |
整數 → Double。 |
i.to_uint() |
有號 → 無號(按位重新解釋)。 |
d.to_int() |
Double → Int,截斷小數部分。 |
d.to_int64() |
Double → Int64。 |
b.to_int() |
Byte → Int。 |
f.to_double() |
Float → Double。 |
c.to_int() |
Char → Unicode 碼點。 |
Char::from_int(66) |
碼點 → Char。 |
i.to_string() |
轉字串。 |
i.to_string(radix=16) |
指定進位輸出;注意字面量呼叫要加括號:(42).to_string(radix=16)。 |
@string.parse_int("42") |
字串 → 整數,失敗 raise。 |
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")
}
| 範例 |
說明 |
(-3).abs() 或 Int::abs(-3) |
絕對值。 |
d.sqrt() |
平方根。 |
@math.pow(2.0, 10.0) |
次方運算;d.pow() 已棄用,改用 @math.pow。 |
d.floor() / d.ceil() / d.round() |
向下 / 向上取整、四捨五入。 |
@math.trunc(d) |
截斷小數部分。 |
@math.sin(x) / @math.cos(x) / @math.tan(x) |
三角函式。 |
@math.ln(x) / @math.log2(x) / @math.log10(x) |
對數。 |
@math.exp(x) |
指數函式。 |
@math.hypot(x, y) |
直角三角形斜邊。 |
Float 版本 |
上述函式多有 f 後綴版本,如 @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")
}
> 注意 错 —— 浮點比較不要寫 a == b;用差值閾值:(a - b).abs() < 1e-9。NaN 與任何值(包括自身)都不相等。
> 效能 —— 整數運算預設 32 位元;需要大範圍計數(位元組數、時間戳記)時明確用 Int64 / UInt64,避免溢位後再排查。
JSON 支援分兩層:#derive(ToJson, FromJson) 做型別級序列化,@json.Json 提供動態樹操作。
| 範例 |
說明 |
#derive(ToJson) |
為結構體 / 列舉產生序列化實作。 |
#derive(FromJson) |
產生反序列化實作。 |
#derive(ToJson, FromJson, Eq) |
一起衍生,方便往返測試。 |
@json.to_json(value) |
任意 ToJson 值 → Json。 |
json.stringify() |
Json → 精簡字串。 |
json.stringify(indent=2) |
帶縮排的格式化輸出。 |
@json.parse(text) |
字串 → Json,失敗時 raise ParseError。 |
@json.from_json(json) |
Json → 具體型別,失敗時 raise JsonDecodeError。 |
@json.valid(text) |
是否為合法 JSON,回傳 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")
}
| 建構 |
說明 |
@json.Json::object(map) |
物件,參數是 Map[String, Json]。 |
@json.Json::array(arr) |
陣列,參數是 Array[Json]。 |
@json.Json::string("x") |
字串值。 |
@json.Json::number(1.0) |
數字值(內部是 Double)。 |
@json.Json::boolean(true) |
布林值。 |
@json.Json::null() |
null 值;Json::Null 是唯讀建構子,不能直接建立。 |
| 讀取 |
說明 |
j.value("key") |
物件欄位,回傳 Json?。 |
j.item(0) |
陣列元素,回傳 Json?。 |
j.as_string() |
取字串,型別不符回傳 None。 |
j.as_number() |
取數字(Double?)。 |
j.as_bool() / j.as_null() |
取布林 / null。 |
j.as_array() |
取陣列,回傳 Array[Json]?。 |
j.as_object() |
取物件,回傳 Map[String, Json]?。 |
match j { Json::Object(m) => ...; _ => ... } |
直接模式匹配七種建構子。 |
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")
}
| 衍生寫法 |
效果 |
#derive(ToJson(style="legacy")) |
{"$tag":"A","x":1},保留標籤欄位。 |
#derive(ToJson(style="flat")) |
["A", 1],更精簡。 |
#derive(FromJson(style="legacy")) |
與對應樣式配對使用。 |
#derive(ToJson(fields(x(rename="X")))) |
欄位重新命名(粗粒度控制)。 |
> 注意 —— 衍生參數只適合粗粒度調整;需要精確控制欄位佈局時,手寫 impl ToJson for T with to_json(self) { ... }。
> 注意 错 —— Json 的 Number 用 Double 儲存,超過 2^53 的整數會遺失精度;需要精確保留大整數時,用 preserve_number_repr=true 解析,或把大整數編碼成字串。
async fn 宣告非同步函式;呼叫端不需要 await,直接寫 let v = f() 即可拿到結果。
| 範例 |
說明 |
async fn f() -> Int { 1 } |
宣告非同步函式,回傳型別仍是 Int。 |
let v = f() |
呼叫非同步函式,結果直接是 Int;編譯器自動等待。 |
@async.pause() |
讓出執行權,等待下一輪排程。 |
async test "name" { ... } |
非同步測試,moon test 支援。 |
async fn f() -> Int raise E { ... } |
非同步 + 錯誤宣告可組合。 |
f() catch { _ => 0 } |
非同步呼叫的錯誤處理與同步一致。 |
async fn fetch(n : Int) -> Int {
@async.pause()
n * 2
}
async test "async" {
let v = fetch(3)
inspect(v, content="6")
}
| 範例 |
說明 |
@async.all([f1, f2]) |
並行執行全部任務,依序回傳結果陣列。 |
@async.all(tasks, max_concurrency=4) |
限制最大並行數。 |
@async.any([f1, f2]) |
回傳最先完成的結果。 |
@async.any(tasks, allow_failure=true) |
允許失敗的任務參與競爭。 |
@async.now() |
目前時間戳記(Int64)。 |
@async.is_being_cancelled() |
目前任務是否已被取消。 |
@async.protect_from_cancel(f) |
執行期間屏蔽取消。 |
@async.handle_cancellation(f) |
把取消轉成 Option:被取消回傳 None。 |
async test "concurrency" {
let xs = @async.all([fn() { fetch(1) }, fn() { fetch(2) }])
inspect(xs, content="[2, 4]")
}
| 寫法 |
說明 |
@async.is_being_cancelled() |
在長任務中輪詢,主動離開。 |
@async.handle_cancellation(f) |
擷取取消,回傳 X?。 |
@async.protect_from_cancel(f) |
關鍵區段不允許被取消。 |
@async.pause() |
取消通常發生在讓出點。 |
> 注意 —— 取消是協作式的:任務不檢查 is_being_cancelled()、也不經過 pause(),就不會被中斷。
> 慣用法 荐 —— 把並行任務寫成 fn() { ... } 閉包傳給 @async.all,比手工維護任務佇列簡單得多;需要限流時用 max_concurrency。
同一份 MoonBit 程式碼可以編譯到四個後端;FFI 宣告依後端區分,透過條件編譯隔離。
| 範例 |
說明 |
|
extern "C" fn f(x : Int) -> Int = "sym" |
Native 後端:連結 C 符號 sym。 |
|
extern "js" fn f() -> Double = "() => Date.now()" |
JS 後端:函式主體直接寫 JavaScript。 |
|
extern "wasm" fn f() -> Int = "env" "f" |
Wasm 後端:匯入模組 env 的函式 f;內聯函式寫作 # |
(func ...),且不提供函式名稱。 |
#external type Handle |
外部不透明型別:wasm 為 externref,js 為 any,native 為 void*。 |
|
#borrow(params..) / #owned(params..) |
C FFI 指標參數的所有權標註;params 是參數名稱子集,需寫在 extern 宣告之前。 |
|
#export_name("name") |
匯出符號名稱;只能用於 pkgtype(kind: "foreign_library") 的套件。 |
|
extern "js" fn now_ms() -> Double = "() => Date.now()"
test "js ffi" {
inspect(now_ms() > 0.0, content="true")
}
| 目標 |
產物 |
典型用途 |
wasm |
.wasm 線性記憶體模組 |
瀏覽器、邊緣函式、外掛。 |
wasm-gc |
使用 Wasm GC 的模組 |
更小的產物,直接與宿主 GC 協作。 |
js |
JavaScript(ESM / CJS / IIFE) |
Node.js、前端整合。 |
native |
原生執行檔 |
CLI、伺服器端。 |
llvm |
經由 LLVM 的原生程式碼 |
需要 LLVM 最佳化的場景。 |
| 命令 |
說明 |
moon build --target js |
指定後端建置。 |
moon check --target all |
對所有後端做型別檢查。 |
moon run --target js cmd/main |
以指定後端執行。 |
moon test --target wasm-gc |
在指定後端跑測試。 |
| 寫法 |
說明 |
#cfg(target="js") |
僅在 JS 後端編譯該宣告。 |
#cfg(platform="windows") |
僅在 Windows 原生建置中編譯。 |
#cfg(not(target="js")) |
取反。 |
#cfg(all(target="native", platform="linux")) |
同時滿足多個條件。 |
#cfg(any(target="js", target="wasm")) |
滿足任一條件。 |
#cfg(false) |
暫時排除一段程式碼(比註解更安全)。 |
#cfg(target="js")
extern "js" fn host_now() -> Double = "() => Date.now()"
#cfg(target="native")
extern "C" fn host_now() -> Double = "monotonic_now"
| 設定 |
說明 |
pkgtype(kind: "executable") |
可執行套件,必須提供 fn main。 |
pkgtype(kind: "foreign_library") |
匯出符號給外部呼叫的函式庫,配合 #export_name。 |
options(targets: { "a.mbt": ["js"] }) |
依後端篩選原始碼檔案。 |
options(targets: { "b.mbt": ["not", "js"] }) |
排除某個後端。 |
warnings = "-2-29" |
關閉指定警告(如未使用變數、未使用套件)。 |
options(
targets: {
"platform_js.mbt": [ "js" ],
"platform_native.mbt": [ "native" ],
"platform_wasm.mbt": [ "wasm", "wasm-gc" ],
},
)
> 注意 错 —— extern "C" 在 wasm / js 後端會直接編譯失敗,extern "js" 在 native 後端同樣失敗。把不同後端的 FFI 放進不同檔案,用 options(targets: ...) 或 #cfg 隔離。
> 注意 —— 修改 moon.pkg 後需要重新執行 moon check;套件設定不會被熱重載。
理解這三件事,能解釋大部分 MoonBit 的行為:多後端編譯、參照語意 + GC、語法糖展開。
| 階段 |
說明 |
| 原始碼 |
.mbt 原始碼檔案,依目錄組成套件,依 moon.mod 組成模組。 |
| 型別檢查 |
moon check 只檢查不產碼;同時產生 .mbti 介面檔案。 |
| 單態化 |
泛型在編譯期依實際型別展開,執行階段沒有型別抹除開銷。 |
| 後端產碼 |
依目標產生 wasm / wasm-gc / js / native 產物。 |
| 執行 |
wasm 用 moonrun,js 用 Node/瀏覽器,native 直接執行。 |
| 概念 |
對應物 |
| 模組(module) |
一個 moon.mod,發布到 mooncakes 的單位。 |
| 套件(package) |
一個目錄 + moon.pkg,是可見性邊界。 |
介面(.mbti) |
moon info 產生的套件公開簽章,用於快速審查 API 變動。 |
| 事實 |
含義 |
| 有 GC |
不需要手寫釋放,也沒有生命週期標註。 |
| 預設參照語意 |
陣列、Map、含 mut 欄位的結構體傳入函式後是同一份資料。 |
| 不可變值可被最佳化複製 |
語意上仍是值,編譯器可自行決定複製時機。 |
Ref[T] |
給原始型別(Int、Double 等)提供可按參照修改的儲存格。 |
| 無 null |
用 Option[T] / T? 表達缺失。 |
| 字串不可變 |
所有「修改」都回傳新 String。 |
struct Counter {
mut value : Int
}
fn bump(c : Counter) -> Unit {
c.value = c.value + 1 // 修改的是呼叫端的物件
}
test "reference semantics" {
let c = Counter::{ value: 0 }
bump(c)
inspect(c.value, content="1")
}
| 想要的效果 |
寫法 |
| 函式內修改呼叫端的結構體 |
欄位宣告 mut,直接賦值。 |
| 函式內修改呼叫端的整數 |
參數用 Ref[Int],讀寫 r.val。 |
| 函式內不修改呼叫端 |
傳入副本:a.copy()、a[:].to_array(),或建構新值。 |
| 共享可變狀態 |
Ref[T] + 閉包,或含 mut 欄位的結構體。 |
| 寫法 |
展開為 |
a + b |
Add::add(a, b) |
-a |
Neg::neg(a) |
a == b |
Eq::equal(a, b) |
a < b |
Compare::compare(a, b) 的結果與 0 比較 |
a[i] |
at(a, i) |
a[i] = v |
set(a, i, v) |
a[1:3] |
視圖切片(ArrayView / StringView) |
for x in xs |
呼叫 xs.iter() 並逐個取出 |
"{x}" |
用 Show 把 x 算繪進字串 |
x |> f |
f(x) |
p.area() |
Type::area(p) |
S::{ x: 1 } |
結構體字面量建構 |
if c { a } else { b } |
三元運算式(有回傳值) |
test "name" { ... } |
註冊一個測試案例 |
> 提示 —— 遇到「型別不匹配」時,先把語法糖展開成明確呼叫(例如把 a + b 寫成 Add::add(a, b)),錯誤訊息往往立刻變得清晰。
這一節是觀點而非規範:讓程式碼更短、更清晰、更快的一些習慣。
| 習慣 |
原因 |
用運算式代替 return |
if/match/迴圈本身有值,函式主體最後一行就是回傳值。 |
用 Option[T] 代替哨兵值 |
-1、""、null 都不如 None 明確。 |
用 match 窮盡分支 |
編譯器強制涵蓋所有建構子,新增分支時不會漏。 |
用 guard ... else 提前離開 |
把異常路徑放前面,主流程保持平鋪。 |
錯誤型別用 suberror 列舉 |
呼叫端可以依建構子分支,而不是匹配錯誤字串。 |
解析時用 StringView |
s[a:b]、split 都不複製,適合處理大輸入。 |
公開結構體預設 pub,需要外部建構才 pub(all) |
縮小 API 面,避免外部繞過不變量。 |
給型別加 #derive(Debug, Eq) |
除錯輸出與比較幾乎總是需要。 |
| 參數多時用標籤參數 |
呼叫點可讀:create_window(title="x", width=800)。 |
| 一個目錄一個內聚的套件 |
套件是可見性邊界,也是編譯與快取的單位。 |
// 推薦:運算式 + guard + match
fn classify(x : Int) -> String {
guard x >= 0 else { return "negative" }
match x {
0 => "zero"
1..=9 => "digit"
_ => "large"
}
}
| 建議 |
說明 |
迴圈串接用 StringBuilder |
s = s + piece 每次都配置新字串。 |
大陣列走訪用 ArrayView |
a[:] 與 a[1:3] 不複製底層資料。 |
長度固定的緩衝區用 FixedArray |
避免動態擴充與額外的容量欄位。 |
需要頻繁依索引存取時用 Array |
Map 有雜湊開銷,適合稀疏鍵。 |
避免不必要的 to_string |
字串配置是常見熱點;日誌等級關閉時不要建構訊息。 |
| 熱路徑用具體型別而非泛型 |
泛型會單態化,通常沒問題;但過度泛化會增加編譯產物。 |
發布建置加 --release |
關閉除錯檢查並取得最佳化。 |
用 moon bench 量化 |
不要憑直覺最佳化;先測量再改。 |
> 提醒 —— MoonBit 的陣列、Map 是參照語意,函式簽章不會複製資料;真正需要副本時才呼叫 copy(),不要習慣性地防禦性複製。
| 陷阱 |
正確做法 |
用 s.length() 數「字元」 |
用 s.char_length();length() 是 UTF-16 code unit。 |
重複消費同一個 Iter |
迭代器是一次性的;多次走訪請先 collect()。 |
| 以為陣列傳參是複製 |
陣列是參照,函式內修改會影響呼叫端。 |
在頂層寫 let mut |
頂層綁定不可變;用 Ref 或結構體欄位。 |
let Some(x) = opt |
可失敗解構用 match / guard ... else / if ... is。 |
42.to_string() |
整數字面量呼叫方法要加括號:(42).to_string()。 |
| 結構體字面量型別歧義 |
加型別標註或寫 Type::{ ... }。 |
在 for 外使用 0..<n |
區間可直接用於 for .. in 和清單推導;其他位置需先收集成陣列。 |
忘記 mut 欄位 |
欄位預設不可變,修改前先在宣告處加 mut。 |
| 整數除法當浮點用 |
7 / 2 == 3;需要小數先轉 Double。 |
| 舊寫法 弃 |
新寫法 |
try? expr |
try Ok(expr) catch { e => Err(e) } |
derive(Show, Eq) |
#derive(Debug, Eq)(放在宣告前) |
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 { ... } 或 while true { ... } |
視圖上的 .to_string() |
.to_owned() |
> 建議 —— 升級工具鏈後先跑 moon fmt(會遷移部分舊語法),再跑 moon check,依棄用警告逐條替換;moon explain --diagnostic <编号> 可以查看每條診斷的官方說明。
| 專案 |
說明 |
| 內容 |
MoonBit 語法、標準函式庫、工具鏈與慣用法速查。 |
| 驗證 |
關鍵程式碼範例在本儲存庫的 examples/ 中用 moon check / moon test 編譯驗證。 |
| 產生器 |
用 Fus 建置:tools/prepare.mbtx 預處理 _chapters/ 下四種語言的原始檔,Fus 輸出 /、/zh-tw/、/en/、/ja/ 四個頁面。 |
| 語言 |
简体中文、繁體中文、English、日本語,可在右上角切換,錨點在各語言間保持一致。 |
| 內容授權 |
CC BY-SA 4.0。 |
| 程式碼授權 |
Apache-2.0。 |
| 工具鏈 |
moonc 1.0.0-rc1。 |
| 操作 |
說明 |
| 點擊右上角 PDF 按鈕 |
呼叫瀏覽器列印對話框。 |
| 快速鍵 <kbd>P</kbd> |
同上。 |
| 目標選擇「另存為 PDF」 |
得到 A4 單欄、去掉互動控制項的列印版。 |
| 列印樣式 |
自動隱藏導覽與按鈕,壓縮字級,表格跨頁不斷行。 |
> 提示 —— 列印版依 A4 單欄排版,適合歸檔與離線查閱;需要雙欄小冊子時,可在列印對話框裡調整縮放與頁邊距。
| 方式 |
說明 |
| 回報錯誤 |
指出章節錨點 + 期望行為 + 實際輸出。 |
| 修正內容 |
改對應語言的原始檔:簡體中文在 _chapters/*.md,其餘在 _chapters/{zh-tw,en,ja}/。改完在 examples/ 補一個可編譯範例。 |
| 新增章節 |
新建 _chapters/NN-name.md,用 # 標題 {#anchor} 開頭即可進入目錄;另外三種語言需在各自目錄放同名檔案。 |
| 本機預覽 |
執行 ./build.sh,然後開啟 public/index.html。 |