The Default
Trait
Default
trait produces a default value for a type.
Speaker Notes
This slide should take about 5 minutes.
- It can be implemented directly or it can be derived via
#[derive(Default)]
. - A derived implementation will produce a value where all fields are set to their default values.
- This means all types in the struct must implement
Default
too.
- This means all types in the struct must implement
- Standard Rust types often implement
Default
with reasonable values (e.g.0
,""
, etc). - 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.