How can I unpack a tuple struct like I would a classic tuple?

六眼飞鱼酱① 提交于 2019-12-22 03:36:44

问题


I can unpack a classic tuple like this:

let pair = (1, true);
let (one, two) = pair;

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;

Results in this error:

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?


回答1:


It's simple: just add the type name!

struct Matrix(f32, f32, f32, f32);

let mat = Matrix(1.1, 1.2, 2.1, 2.2);
let Matrix(one, two, three, four) = mat;
//  ^^^^^^

This works as expected.


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;


来源:https://stackoverflow.com/questions/45624813/how-can-i-unpack-a-tuple-struct-like-i-would-a-classic-tuple

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!