From ab831de1da4612e6f1fac5e81891f13dae78d970 Mon Sep 17 00:00:00 2001 From: Igor Petruk Date: Mon, 6 Feb 2023 19:17:21 +0000 Subject: [PATCH] Suggesting to add `Default` to important traits. (#243) * Suggesting to add `Default` to important traits. This is a great trait to know about, it is used very often. * Change `Implemented` to tuple struct. It saves vertical space. --- src/SUMMARY.md | 1 + src/traits/default.md | 47 ++++++++++++++++++++++++++++++++++ src/traits/important-traits.md | 1 + 3 files changed, 49 insertions(+) create mode 100644 src/traits/default.md diff --git a/src/SUMMARY.md b/src/SUMMARY.md index fe3237de..f131f778 100644 --- a/src/SUMMARY.md +++ b/src/SUMMARY.md @@ -134,6 +134,7 @@ - [Read and Write](traits/read-write.md) - [Add, Mul, ...](traits/operators.md) - [Drop](traits/drop.md) + - [Default](traits/default.md) - [Generics](generics.md) - [Generic Data Types](generics/data-types.md) - [Generic Methods](generics/methods.md) diff --git a/src/traits/default.md b/src/traits/default.md new file mode 100644 index 00000000..a19c8d01 --- /dev/null +++ b/src/traits/default.md @@ -0,0 +1,47 @@ +# The `Default` Trait + +`Default` trait provides a default implementation of a trait. + +```rust,editable +#[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::default(); + println!("{default_struct:#?}"); + + let almost_default_struct = Derived { + y: "Y is set!".into(), + ..Default::default() + }; + println!("{almost_default_struct:#?}"); + + let nothing: Option = None; + println!("{:#?}", nothing.unwrap_or_default()); +} + +``` + +
+ + * 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. + +
diff --git a/src/traits/important-traits.md b/src/traits/important-traits.md index 068756d9..22900166 100644 --- a/src/traits/important-traits.md +++ b/src/traits/important-traits.md @@ -7,3 +7,4 @@ We will now look at some of the most common traits of the Rust standard library: * `Read` and `Write` used for IO, * `Add`, `Mul`, ... used for operator overloading, and * `Drop` used for defining destructors. +* `Default` used to construct a default instance of a type.