How can I unpack a tuple structure, like a classic tuple?

I can unpack the classic tuple as follows:

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

If I have a tuple structure such as struct Matrix(f32, f32, f32, f32), and I try to unpack it, I get an "unexpected type" error message:

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

Results of 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 structure? Does it need to be explicitly converted to a tuple type? Or do I need to hard record it?

+4
source share
1 answer

It is simple: just add a 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.


, . , (, height):

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

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

Source: https://habr.com/ru/post/1683480/


All Articles