有没有办法部分解构结构?

Is there a way to destructure a struct partially?

我有一个结构:

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

并且我想在实例化后提取三个属性中的两个

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

编译器抛出以下错误:

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`

在 JavaScript (ES6) 中,等效的解构看起来像这样:

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

.. 作为 struct 或元组模式中的字段表示“和其余”:

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

the Rust Book 中有更多相关内容。

您可以像这样部分解构结构:

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