Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to destructure a struct partially?

Tags:

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; 
like image 927
Tom Avatar asked Aug 20 '17 12:08

Tom


People also ask

How destructuring works in arrays and objects in JavaScript?

Let's see how destructuring works in arrays and objects now. To destructure an array in JavaScript, we use the square brackets [] to store the variable name which will be assigned to the name of the array storing the element.

What is destructuring and how to do it?

The very first thing you have to do is to search through your collection and unpack whatever you have there. Now destructuring is just like that approach you took when looking for your shoes. Destructuring is the act of unpacking elements in an array or object.

How to destruct an object without declaration?

Object destructuring Basic assignment Assignment without declaration Assigning to new variable names Default values Assigning to new variables names and providing default values Unpacking fields from objects passed as function parameter Setting a function parameter's default value Nested object and array destructuring

What is destructuring assignment syntax?

The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables. The source for this interactive example is stored in a GitHub repository.


1 Answers

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

like image 159
DK. Avatar answered Oct 20 '22 09:10

DK.