如何像解压经典元组一样解压元组结构?

2024-06-22

我可以像这样解压一个经典元组:

let pair = (1, true);
let (one, two) = pair;

如果我有一个元组结构,例如struct Matrix(f32, f32, f32, f32)我尝试解压它,收到有关“意外类型”的错误:

struct Matrix(f32, f32, f32, f32);
let mat = Matrix(1.1, 1.2, 2.1, 2.2);
let (one, two, three, four) = mat;

结果出现此错误:

error[E0308]: mismatched types
  --> src/main.rs:47:9
   |
47 |     let (one, two, three, four) = mat;
   |
   = note: expected type `Matrix`
              found type `(_, _, _, _)`

如何解压元组结构?我需要将其显式转换为元组类型吗?或者我需要对其进行硬编码?


这很简单:只需添加类型名称即可!

struct Matrix(f32, f32, f32, f32);

let mat = Matrix(1.1, 1.2, 2.1, 2.2);
let Matrix(one, two, three, four) = mat;
//  ^^^^^^

这按预期工作。


它的工作原理与普通结构完全相同。在这里,您可以绑定到字段名称或自定义名称(例如height):

struct Point {
    x: f64,
    y: f64,
}

let p = Point { x: 0.0, y: 5.0 };
let Point { x, y: height } = p;

println!("{x}, {height}");
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何像解压经典元组一样解压元组结构? 的相关文章

随机推荐