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.

Example:

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

This produces

error[E0308]: mismatched types
   --> src/main.rs:109:9
    |
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?
https://doc.rust-lang.org/book/ch18-03-pattern-syntax.html?highlight=destructur#destructuring-structs-and-tuples

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;
6 Likes

That is the correct answer.

https://play.rust-lang.org/?version=nightly&mode=debug&edition=2018&gist=47ae995ab478a222bd0338ce8a23c80a

2 Likes

@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.

https://play.rust-lang.org/?version=nightly&mode=debug&edition=2018&gist=aa8f3fdc90ec395a259e21230225bb8f

@Hyeonu

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.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.