Default 特征

Default 特征会为类型生成默认值。

#[derive(Debug, Default)]
struct Derived {
    x: u32,
    y: String,
    z: Implemented,
}

#[derive(Debug)]
struct Implemented(String);

impl Default for Implemented {
    fn default() -> Self {
        Self("John Smith".into())
    }
}

fn main() {
    let default_struct = Derived::default();
    println!("{default_struct:#?}");

    let almost_default_struct = Derived {
        y: "Y is set!".into(),
        ..Derived::default()
    };
    println!("{almost_default_struct:#?}");

    let nothing: Option<Derived> = None;
    println!("{:#?}", nothing.unwrap_or_default());
}
  • 系统可以直接实现它,也可以通过 #[derive(Default)] 派生出它。
  • A derived implementation will produce a value where all fields are set to their default values.
    • 这意味着,该结构体中的所有类型也都必须实现 Default
  • 标准的 Rust 类型通常会以合理的值(例如 0“” `等)实现Default`。
  • 部分结构体副本可与默认值完美搭配运作。
  • Rust 标准库了解类型可能会实现 Default,因此提供了便利的使用方式。
  • “..”语法被称为结构体更新语法