Default 特征

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

  1. #[derive(Debug, Default)]
  2. struct Derived {
  3. x: u32,
  4. y: String,
  5. z: Implemented,
  6. }
  7. #[derive(Debug)]
  8. struct Implemented(String);
  9. impl Default for Implemented {
  10. fn default() -> Self {
  11. Self("John Smith".into())
  12. }
  13. }
  14. fn main() {
  15. let default_struct = Derived::default();
  16. println!("{default_struct:#?}");
  17. let almost_default_struct =
  18. Derived { y: "Y is set!".into(), ..Derived::default() };
  19. println!("{almost_default_struct:#?}");
  20. let nothing: Option<Derived> = None;
  21. println!("{:#?}", nothing.unwrap_or_default());
  22. }

This slide should take about 5 minutes.

  • 系统可以直接实现它,也可以通过 #[derive(Default)] 派生出它。
  • A derived implementation will produce a value where all fields are set to their default values.
    • 这意味着,该结构体中的所有类型也都必须实现 Default
  • 标准的 Rust 类型通常会以合理的值(例如 0“” `等)实现Default`。
  • The partial struct initialization works nicely with default.
  • The Rust standard library is aware that types can implement Default and provides convenience methods that use it.
  • The .. syntax is called struct update syntax.