rust-unofficial / patterns

A catalogue of Rust design patterns, anti-patterns and idioms
https://rust-unofficial.github.io/patterns/
Mozilla Public License 2.0
7.95k stars 362 forks source link

Example of using Default::default with a struct #156

Open insanitybit opened 3 years ago

insanitybit commented 3 years ago

The book currently suggests that Default::default is useful for when you want to be generic over construction, but I would argue that that's rarely why you want default, and instead that use case is much better satisfied by taking a closure.

Instead, I think Default is almost exclusively useful for cases like this:

let some_val = MyStruct {
  val_a: 1234,
  ..Default::default()
};

let other_val = MyStruct {
  val_c: "other thing",
  ..some_val,
};

There are some cases where 'default' construction is used as a generic, like on Option::unwrap_or_default, but unsurprisingly I see unwrap_or and unwrap_or_else used far more often.