Tom*_*Tom 9 destructuring rust
我有一个结构:
struct ThreeDPoint {
x: f32,
y: f32,
z: f32
}
Run Code Online (Sandbox Code Playgroud)
我想在实例化之后提取三个属性中的两个:
let point: ThreeDPoint = ThreeDPoint { x: 0.3, y: 0.4, z: 0.5 };
let ThreeDPoint { x: my_x, y: my_y } = point;
Run Code Online (Sandbox Code Playgroud)
编译器抛出以下错误:
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`
Run Code Online (Sandbox Code Playgroud)
在JavaScript(ES6)中,等效的解构将如下所示:
let { x: my_x, y: my_y } = point;
Run Code Online (Sandbox Code Playgroud)
DK.*_*DK. 16
..作为一个struct或元组模式中的字段意味着"和其余":
let ThreeDPoint { x: my_x, y: my_y, .. } = point;
Run Code Online (Sandbox Code Playgroud)
在Rust Book中有更多关于此的内容.
小智 5
您可以像这样对结构进行部分解构:
let point = ThreeDPoint { x: 0.3, y: 0.4, z: 0.5 };
let ThreeDPoint { my_x, my_y, .. } = point;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1436 次 |
| 最近记录: |