Skip to content
Tutorials Center
My learning

Topics

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.

Rust
#[derive(Default)]
struct Config { retries: u32, verbose: bool }

Try it

Rust Deriving Default and struct update

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.

Rust Enums, manual impls and helpers

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

Rust
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 0 or an empty string makes an invalid state, write a manual impl (as Timeout does above) or do not implement Default at all.
  • Struct update syntax: Struct { field: value, ..Default::default() } fills the remaining fields. It moves non-Copy fields 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() and Vec::resize_with(n, Default::default).
  • Default for &str is "" and for &[T] is the empty slice, but there is no default for &T in general or for fn types.
  • References and Box: Box<T> is Default when T is; Rc<T> and Arc<T> likewise.
  • Generics: #[derive(Default)] adds a T: Default bound automatically, which can be stricter than you need. Implement it by hand if only some type parameters really need it.