How to destructure a tuple struct?

Rust Book nightly:

Using Tuple Structs without Named Fields to Create Different Types

Otherwise, tuple struct instances behave like tuples: you can destructure them into their individual pieces ...

I'm trying to understand destructuring a tuple struct into primitive variables.


struct Point(i32, i32, i32);
let origin = Point(0, 0, 0);
let (h, w, d) = origin;

This produces

error[E0308]: mismatched types
   --> src/
109 |     let (h, w, d) = origin;
    |         ^^^^^^^^^   ------ this expression has type `main::Point`
    |         |
    |         expected struct `main::Point`, found tuple
    = note: expected struct `main::Point`
                found tuple `(_, _, _)`

The goal here is to recreate h, w and d as individual i32 variables.
Any hints on how to destructure a tuple struct are greatly appreciated.

I am not sure, but did you tried out let Point(h,w,d) = origin?

1 Like

Constructor syntax is designed to be symmetric with pattern syntax.

let &x = &42;
let (a, b, c) = (7, 8, 9);
let Foo {bar: x, baz: y} = Foo {bar: 42, baz: 43};
let Point(h, w, d) = Point(h, w, d);

So, this is what you want.

let origin = Point(0, 0, 0);
let Point(h, w, d) = origin;

That is the correct answer.


@bug00r let Point(h,w,d) = origin is the correct answer, it worked in my example code. :slight_smile:

I can see why you might not be sure, the section you linked only confuses me and I don't see how you arrived at the answer from that material. But then, I'm only on Chapter 5 and the destructuring material you linked is chapter 18.

@ekuber Thanks for the playground example.

I added println!("origin\n H:{} W:{} D:{}", h, w, d); to your example to eliminate the unused variable warnings and show the code producing the desired result.


Constructor syntax is designed to be symmetric with pattern syntax.

I hadn't noticed that. A simple but significant point in Rust. Thanks for pointing it out and adding to my foundational understanding.