gihrig
July 3, 2020, 5:46am
#1
Rust Book nightly:
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.
2 Likes
bug00r
July 3, 2020, 5:47am
#2
3 Likes
Hyeonu
July 3, 2020, 5:49am
#3
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;
10 Likes
ekuber
July 3, 2020, 5:49am
#4
2 Likes
gihrig
July 3, 2020, 4:33pm
#5
@bug00r let Point(h,w,d) = origin
is the correct answer, it worked in my example code.
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.
1 Like
system
closed
October 1, 2020, 4:47pm
#7
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.