Rust Reference ยท Core Traits
The Default trait
Reference for the Rust Default trait: default values for std types, #[derive(Default)] on structs and enums with #[default], and struct update syntax.
Default gives a type a canonical "empty" or "starting" value, written T::default(). Numbers default to zero, bool to false, String and Vec<T> to empty, Option<T> to None, and tuples, arrays and structs to the defaults of their parts.
It is most useful for configuration structs, together with struct update syntax (..Default::default()), and in generic code that needs a starting value, such as mem::take or unwrap_or_default.
#[derive(Default)] struct Config { retries: u32, verbose: bool }
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Syntax
pub trait Default: Sized { fn default() -> Self; }
| Name | Description |
|---|---|
| (none) | default takes no arguments. Call it as T::default(), Default::default() with a known target type, or <T as Default>::default(). |
Returns: a value of Self.
Derive: #[derive(Default)] works for structs whose fields all implement Default, and for enums when exactly one unit variant is marked #[default]. Without the attribute, an enum derive does not compile.
Usage notes
- Zero is not always the right default. If
0or an empty string makes an invalid state, write a manual impl (asTimeoutdoes above) or do not implementDefaultat all. - Struct update syntax:
Struct { field: value, ..Default::default() }fills the remaining fields. It moves non-Copyfields out of the temporary base, which is fine for a freshly built default. - Helpers that use it:
Option::unwrap_or_default,Result::unwrap_or_default,mem::take(replaces a value with its default and returns the old one),HashMap::entry(..).or_default()andVec::resize_with(n, Default::default). Defaultfor&stris""and for&[T]is the empty slice, but there is no default for&Tin general or forfntypes.- References and
Box:Box<T>isDefaultwhenTis;Rc<T>andArc<T>likewise. - Generics:
#[derive(Default)]adds aT: Defaultbound automatically, which can be stricter than you need. Implement it by hand if only some type parameters really need it.