05-结构体

结构体 — Rust By Example

译文 · 基于 Rust By Example

原文链接: https://doc.rust-lang.org/stable/rust-by-example/flow_control/match/destructuring/destructure_structures.html

结构体

​ 类似地,解构 struct 如下所示:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
fn main() {
    struct Foo { x: (u32, u32), y: u32 }

    // 解构结构体的成员
    let foo = Foo { x: (1, 2), y: 3 };
    let Foo { x: (a, b), y } = foo;

    println!("a = {}, b = {},  y = {} ", a, b, y);//a = 1, b = 2,  y = 3 

    // 可以解构结构体并重命名变量,成员顺序并不重要

    let Foo { y: i, x: j } = foo;
    println!("i = {:?}, j = {:?}", i, j);//i = 3, j = (1, 2)

    // 也可以忽略某些变量
    let Foo { y, .. } = foo;
    println!("y = {}", y);//y = 3

    // 这将得到一个错误:模式中没有提及 `x` 字段
    // let Foo { y } = foo;
}

参见:

结构体, ref 模式

最后修改 October 2, 2026: 更新 (f3447ada6)