我可以像这样解压一个经典的元组:
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/