struct - 如何像解包经典元组一样解包元组结构?

标签 struct rust tuples tuple-struct

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

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;
//  ^^^^^^

这按预期工作。


它与普通结构完全一样。在这里,您可以绑定(bind)到字段名称或自定义名称(如 height):

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

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

关于struct - 如何像解包经典元组一样解包元组结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45624813/

相关文章:

python - 将字符串作为元组作为参数传递 python

c++ - vector::erase() 也删除结构的成员 vector

c - 如何制作一个空指针来读取二进制文件的给定部分

data-structures - 将函数应用于 Racket 中的树结构

rust - PNaCl 对 Rust 的支持

ios - 了解函数中的快速代码元组复合

c - Wolfcryp RSA 解析 key 分段失败

rust - 涉及向量时移动闭包关键字

rust - 理解错误 : trait `futures::future::Future` is not implemented for `()`

python - 如何从文件中读取带有字符串键和元组值的字典?