介绍

Move 中有类似元组tuple的表达式,这些表达式在运行时不会产生具体的值(字节码中是不支持元组的)。作用仅仅是支持返回多个值,且只能应用在表达式中(即在函数的返回位置),也不能绑定局部变量、不能存储在struct中、且tuple类型不能使用泛型。

字面量

unit ()是 Move 中的内置类型,unit()运行时不会有任何结果,可以理解为一个空元组:

函数 描述
() 定义一个空元组
(e1, ..., e2) 定义一个有n个元素的元组

举例

  1. address 0x1 {
  2. module Example {
  3. fun return_unit_1() { }
  4. fun return_unit_2(): () { }
  5. fun return_unit_3(): () { () }
  6. fun return_3_value(): (u64, bool, address) {
  7. (0, true, @0x2)
  8. }
  9. fun return_4_value(x: &u64): (&u64, u8, u128, vector<u8>) {
  10. (x, 0, 1, b"foobar")
  11. }
  12. }
  13. }

用法

目前元组tuple的使用就是解构destruct。任何大小的元组,都可以使用let绑定或赋值中被解构:

  1. address 0x1 {
  2. module Example {
  3. fun return_unit() {}
  4. fun return_2_value(): (bool, bool) { (true, false) }
  5. fun return_4_value(x: &u64): (&u64, u8, u128, vector<u8>) { (x, 0, 1, b"hello") }
  6. fun example(cond: bool) {
  7. let () = ();
  8. let (x, y): (u8, u64) = (0, 1);
  9. let (a, b, c, d) = (@0x0, 0, false, b"h");
  10. () = ();
  11. (x, y) = if (cond) (1, 2) else (3, 4);
  12. (a, b, c, d) = (@0x1, 1, true, b"1")
  13. }
  14. fun example_with_call() {
  15. let () = return_unit();
  16. let (x, y): (bool, bool) = return_2_value();
  17. let (a, b, c, d) = return_4_value(&0);
  18. () = return_unit();
  19. (x, y) = return_2_value();
  20. (a, b, c, d) = return_4_value(&1);
  21. }
  22. }
  23. }