Rust结构体更新语法

我们在定义一个新的结构体变量时可以使用已有的成员的属性来更新。

下面的程序使用 结构体更新语法 根据其他结构体实例创建新的结构体实例。

示例程序:

struct Student {
    name: String,
    chinese: u32,
    math: u32,
    science: u32,
    english: u32
}

fn main() {
    let stu1 = Student {
        name: String::from("yuyoubei"),
        chinese: 90,
        math: 100,
        science: 95,
        english: 95,
    };
    println!("{} {} {} {} {}", stu1.name, stu1.chinese, stu1.math, stu1.science, stu1.english);     // 输出 yuyoubei 90 100 95 95

    let stu2 = Student {
        name: String::from("yihan"),
        chinese: 99,
        ..stu1
    };
    println!("{} {} {} {} {}", stu2.name, stu2.chinese, stu2.math, stu2.science, stu2.english);     // 输出 yihan 99 100 95 95
    
    let stu3 = Student {
        ..stu2
    };
    println!("{} {} {} {} {}", stu3.name, stu3.chinese, stu3.math, stu3.science, stu3.english);     // 输出 yihan 99 100 95 95
}

程序中,定义 stu2 时除 name 和 chinese 字段,其余均与 stu1 同;定义 stu3 时的所有属性均与 stu2 同。

使用 ..结构体变量 的形式,在定义一个新的结构体时,将缺省的属性都定义成与 .. 后的 结构体变量 相同。

posted @ 2022-01-30 12:19  鱼又悲  阅读(188)  评论(0编辑  收藏  举报