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;
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.
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.
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
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.
..
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With