The Default Trait

Default trait provides a default implementation of a trait.

  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::default();
  16. println!("{default_struct:#?}");
  17. let almost_default_struct = Derived {
  18. y: "Y is set!".into(),
  19. ..Default::default()
  20. };
  21. println!("{almost_default_struct:#?}");
  22. let nothing: Option<Derived> = None;
  23. println!("{:#?}", nothing.unwrap_or_default());
  24. }
  • It can be implemented directly or it can be derived via #[derive(Default)].
  • Derived implementation will produce an instance where all fields are set to their default values.
    • This means all types in the struct must implement Default too.
  • Standard Rust types often implement Default with reasonable values (e.g. 0, "", etc).
  • The partial struct copy works nicely with default.
  • Rust standard library is aware that types can implement Default and provides convenience methods that use it.