包括+=、-=、*=、/=,支持运算符重载:
fn init { let array = [1,2,3,4] array[2] *= 10 println(array) // [1, 2, 30, 4] } fn init { let mut a = 1 a += 20 println(a) // 21 } struct Foo { data : Array[Int] } derive(Debug) fn op_set(self : Foo, index : Int, value : Int) { self.data[index] = value } fn op_get(self : Foo, index : Int) -> Int { self.data[index] } fn init { let foo : Foo = { data: [0,0,0,0] } foo[2] -= 10 debug(foo) // {data: [0, 0, -10, 0]} }
如下图所示:
Super-trait 通过如下的语法指定:
trait A { // ... } trait B : A { // A is a super trait of B, B is a sub trait of A // ... }
可以通过 + 来指定多个 Super-trait ,表示该 sub-trait 依赖这几个 super-trait:
// ... trait B: A + Compare + Debug { // ^~~ B is a sub-trait of A *and* Compare *and* Debug // ... }
在使用上,可以将 sub-trait 当作 super trait 使用,但是不能够将 super-trait 当作 sub-trait 使用。目前 Compare 是 Eq 的 sub-trait ,意味着实现了 Compare 的类型能够在要求 Eq 的情况下使用,所以以这两个代码为例:
trait Eq { op_equal(Self, Self) -> Bool } trait Compare: Eq { compare(Self, Self) -> Int } fn eq[X: Compare](this: X, that: X) -> Bool { this == that } fn compare[X: Eq](this: X, that: X) -> Int { this.compare(that) // ^~~~~~~ Type X has no method compare. }
这种语法结构会被解糖成 T::from_array([x, y, ...])的形式。这种语法使得列表等线性数据结构的初始化更加易读。
enum List[X] { Nil Cons(X, List[X]) } derive(Show, Debug) fn List::from_array[X](array: Array[X]) -> List[X] { let mut list = List::Nil for i = array.length() - 1; i >= 0; i = i - 1 { list = Cons(array[i], list) } list } fn main { println(List::[1, 2, 3]) }
输出:
Cons(1, Cons(2, Cons(3, Nil)))
现在它会调用 Debug 作为实现。这意味着,现在 derive(Show) 之前需要先 derive 或自行实现 Debug 。Debug 的输出是 MoonBit 语法下合法的值,而 Show 可以用于输出更美观的内容。这修复了之前 derive(Show) 在有 String 的结构体上的错误行为:
struct T { x: String } derive(Show, Debug) fn init { println({ x: "1, y: 2" }) // 之前: {x: 1, y: 2} // 现在: {x: "1, y: 2"} }
fn hello() = "xx"的语法目前已经不适用了。我们建议用户这样写:
extern "wasm" fn hello () = #| ...
现在 inline stubs 只支持 wasmgc ,不支持 wasm1 。
fn f() -> Int { ignore(3) // Ok. 3 |> ignore // Ok. 3 // Err: Expr Type Mismatch: has type Int, wanted Unit 3 // Ok, as this value is returned, not dropped }
p.s. 但是在使用之前,必须再用安装脚本安装一次:-)