39

I have a struct:

struct ThreeDPoint {
    x: f32,
    y: f32,
    z: f32
}

and I want to extract two of the three properties after instantiating it:

let point: ThreeDPoint = ThreeDPoint { x: 0.3, y: 0.4, z: 0.5 };
let ThreeDPoint { x: my_x, y: my_y } = point;

The compiler throws the following error:

error[E0027]: pattern does not mention field `z`
  --> src/structures.rs:44:9
   |
44 |     let ThreeDPoint { x: my_x, y: my_y } = point;
   |         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ missing field `z`

In JavaScript (ES6), the equivalent destructuring would look like this:

let { x: my_x, y: my_y } = point;
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Tom
  • 4,776
  • 2
  • 38
  • 50

2 Answers2

60

.. as a field in a struct or tuple pattern means "and the rest":

let ThreeDPoint { x: my_x, y: my_y, .. } = point;

There's more about this in the Rust Book.

the_morrok
  • 83
  • 5
DK.
  • 55,277
  • 5
  • 189
  • 162
10

You can partially destructure a struct like this:

let point = ThreeDPoint { x: 0.3, y: 0.4, z: 0.5 };
let ThreeDPoint { x: my_x, y: my_y, .. } = point;
EternalObserver
  • 517
  • 7
  • 19
lukwol
  • 264
  • 2
  • 6