我怎样才能像解压经典元组一样解压元组结构? [英] How can I unpack a tuple struct like I would a classic tuple?
本文介绍了我怎样才能像解压经典元组一样解压元组结构?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我可以像这样解压一个经典的元组:
I can unpack a classic tuple like this:
let pair = (1, true);
let (one, two) = pair;
如果我有一个元组结构,例如 struct Matrix(f32, f32, f32, f32)
并且我尝试解压缩它,我会收到关于意外类型"的错误:
If I have a tuple struct such as struct Matrix(f32, f32, f32, f32)
and I try to unpack it, I get an error about "unexpected type":
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 `(_, _, _, _)`
如何解包元组结构?我是否需要将其显式转换为元组类型?还是我需要对其进行硬编码?
How can I unpack a tuple struct? Do I need to convert it explicitly to a tuple type? Or do I need to hardcode it?
推荐答案
很简单:只需添加类型名称即可!
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
):
It works exactly the same with normal structs. Here, you can bind either to the field name or a custom name (like height
):
struct Point {
x: f64,
y: f64,
}
let p = Point { x: 0.0, y: 5.0 };
let Point { x, y: height } = p;
这篇关于我怎样才能像解压经典元组一样解压元组结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文