XU XUv0.16.0

04 · 函式與方法

沒有 class:struct + 方法。值接收者只讀;$& 接收者要求呼叫方繫結為 $。

原始碼

@main

fn add(a int, b int) int {
    << a + b
}

struct Counter {
    n int
}

fn (c Counter) get() int {
    << c.n
}

fn (c $&Counter) inc() {
    c.n += 1
}

fn main() int {
    println(add(2, 3))

    $c := Counter{n: 10}
    println(c.get())
    c.inc()
    println(c.get())
    << 0
}

編譯(examples 倉庫根,使用已安裝的 xu):

xu run examples/04_functions_methods/main.xu
# 或:xu build examples/04_functions_methods/main.xu
# mac/linux 預設寫出 ./main ;Windows 為 ./main.exe

在獨立的 examples 倉庫根執行;原始碼位於 examples/。