MoonBit 本周重磅更新:枚举构造器支持可变字段、数组字面量默认构建 Vector

41 天前
 moonbitlang

MoonBit 更新

enum E {
  C(mut ~x : Int, mut ~y : Int)
} derive(Debug)


fn swap_xy(x : E) -> Unit {
  match x {
    // `~y` 会绑定模式匹配前 `C` 中的 `y` 字段的值
    // 当看到 `C(..) as c` 这种模式时,编译器知道 `c` 一定是构造器 `C`,
    // 所以可以在分支内部用 `c.x`、`c.y` 直接访问 `C` 的字段
    C(~y, ..) as c => {
      // `c.x` 和 `c.y` 可以用于修改/读取 `C` 中最新的值
      c.y = c.x
      c.x = y
    }
  }
}

fn init {
  let e : E = C(x=1, y=2)
  debug(e) // C(x=1, y=2)
  swap_xy(e)
  debug(e) // C(x=2, y=1)
}

这个例子中的 swap_xy 函数对构造器 Cxy 两个 field 的值进行了交换,并且这个交换是 in-place 的,没有引入额外的内存分配

fn init {
  let v = [1, 2, 3]             // v has type @vec.Vec[Int]
  let a : Array[_] = [1, 2, 3]  // a has type Array[Int]
}

接下来两周,我们计划将 Array 重命名为 FixedArray,将 Vec 重命名为 Array,以保证准确反映数据结构的特性,避免与向量混淆。

./vec/sort.mbt:68:16-68:23 [E4021] The value identifier minimum is unbound.
./vec/sort_by.mbt:90:16-90:23 [E4021] The value identifier minimum is unbound.
./vec/vec.mbt:962:37-962:50 [E4020] Package "iter" not found in the loaded packages.
./vec/vec.mbt:963:3-963:13 [E4024] The type/trait @iter.Iter is not found.

IDE 更新

构建系统更新

{
  "warn_list": "-2",
  "alert_list": "-alert_1-alert_2"
}
-b, --bind <BIND> [default: 127.0.0.1]
-p, --port <PORT> [default: 3000]
平台 优化前 优化后
macOS arm64 7.3 MiB 3.6 MiB
macOS x86_64 8.2 MiB 4.1 MiB
Ubuntu x86_64 14.0 MiB 9.6 MiB
Windows x86_64 9.4 MiB 4.9 MiB

工具链更新

  fn bar() -> Unit {
  abort("")
}

fn foo() -> Unit {
  bar()
}

fn main {
  foo()
}

执行 moon run main --debug,可观察到输出类似:

error: RuntimeError: unreachable
    at $username/hello/main.bar.fn/1 (wasm://wasm/6fe99e5e:wasm-function[3]:0xe6)
    at $username/hello/main.foo.fn/2 (wasm://wasm/6fe99e5e:wasm-function[4]:0xea)
    at *init*/3 (wasm://wasm/6fe99e5e:wasm-function[5]:0xef)
    at <anonymous>:9:22
327 次点击
所在节点    编程
0 条回复

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/1040365

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX