eis*_*man 11 struct tuples rust tuple-struct
我可以解压这样的经典元组:
let pair = (1, true);
let (one, two) = pair;
Run Code Online (Sandbox Code Playgroud)
如果我有一个元组结构,如果我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;
Run Code Online (Sandbox Code Playgroud)
结果出现此错误:
error[E0308]: mismatched types
--> src/main.rs:47:9
|
47 | let (one, two, three, four) = mat;
|
= note: expected type `Matrix`
found type `(_, _, _, _)`
Run Code Online (Sandbox Code Playgroud)
如何解压缩元组结构?我是否需要将其显式转换为元组类型?或者我需要硬编码吗?
Luk*_*odt 12
这很简单:只需添加类型名称!
struct Matrix(f32, f32, f32, f32);
let mat = Matrix(1.1, 1.2, 2.1, 2.2);
let Matrix(one, two, three, four) = mat;
// ^^^^^^
Run Code Online (Sandbox Code Playgroud)
这按预期工作.
它与普通结构完全相同.在这里,您可以绑定到字段名称或自定义名称(如height):
struct Point {
x: f64,
y: f64,
}
let p = Point { x: 0.0, y: 5.0 };
let Point { x, y: height } = p;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
655 次 |
| 最近记录: |