Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;

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?

like image 416
eisterman Avatar asked Aug 10 '17 23:08

eisterman


People also ask

How do you unpack a tuple?

Python uses a special syntax to pass optional arguments (*args) for tuple unpacking. This means that there can be many number of arguments in place of (*args) in python. All values will be assigned to every variable on the left-hand side and all remaining values will be assigned to *args .

What does struct unpack return?

The return type of struct. unpack() is always a tuple. The function is given a format string and the binary form of data. This function is used to parse the binary form of data stored as a C structure.

What is packing and unpacking of tuple give example?

Tuple packing refers to assigning multiple values into a tuple. Tuple unpacking refers to assigning a tuple into multiple variables. You have already used tuple packing because it is as simple as: >>> django_movie = ("Tarantino", 2012, 8.4, "Waltz & DiCaprio")


1 Answers

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;
like image 58
Lukas Kalbertodt Avatar answered Oct 06 '22 10:10

Lukas Kalbertodt