介绍
Move 中有类似元组tuple的表达式,这些表达式在运行时不会产生具体的值(字节码中是不支持元组的)。作用仅仅是支持返回多个值,且只能应用在表达式中(即在函数的返回位置),也不能绑定局部变量、不能存储在struct中、且tuple类型不能使用泛型。
字面量
unit ()是 Move 中的内置类型,unit()运行时不会有任何结果,可以理解为一个空元组:
| 函数 | 描述 |
|---|---|
() |
定义一个空元组 |
(e1, ..., e2) |
定义一个有n个元素的元组 |
举例
address 0x1 {module Example {fun return_unit_1() { }fun return_unit_2(): () { }fun return_unit_3(): () { () }fun return_3_value(): (u64, bool, address) {(0, true, @0x2)}fun return_4_value(x: &u64): (&u64, u8, u128, vector<u8>) {(x, 0, 1, b"foobar")}}}
用法
目前元组tuple的使用就是解构destruct。任何大小的元组,都可以使用let绑定或赋值中被解构:
address 0x1 {module Example {fun return_unit() {}fun return_2_value(): (bool, bool) { (true, false) }fun return_4_value(x: &u64): (&u64, u8, u128, vector<u8>) { (x, 0, 1, b"hello") }fun example(cond: bool) {let () = ();let (x, y): (u8, u64) = (0, 1);let (a, b, c, d) = (@0x0, 0, false, b"h");() = ();(x, y) = if (cond) (1, 2) else (3, 4);(a, b, c, d) = (@0x1, 1, true, b"1")}fun example_with_call() {let () = return_unit();let (x, y): (bool, bool) = return_2_value();let (a, b, c, d) = return_4_value(&0);() = return_unit();(x, y) = return_2_value();(a, b, c, d) = return_4_value(&1);}}}
