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

18

我可以这样拆开一个经典的元组:

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

如果我有一个元组结构体,例如struct Matrix(f32, f32, f32, f32),当我尝试解包它时,会出现"意外类型"的错误:

如果我有一个类似于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 `(_, _, _, _)`

我该如何解构一个元组结构体?我需要将其显式转换为元组类型吗?还是需要硬编码实现?

1个回答

29
简单来说:只需添加类型名称!
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}");

2
Rust 是我做过的最好的语言,毫无疑问。 - Anssi
所以在最后一个 "let Point" 之后,你可以使用 println!("{height}"); 并获得输出为 5? - Pieter
1
@Pieter 是的。我编辑了我的回答,包括了那个内容。 - Lukas Kalbertodt

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接