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

问题描述 投票:0回答:1

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

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 rust tuples tuple-struct
1个回答
27
投票

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

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}");
© www.soinside.com 2019 - 2024. All rights reserved.