Trait core::default::Default1.0.0[][src]

pub trait Default: Sized {
    fn default() -> Self;
}
Expand description

A trait for giving a type a useful default value.

Sometimes, you want to fall back to some kind of default value, and don’t particularly care what it is. This comes up often with structs that define a set of options:

struct SomeOptions {
    foo: i32,
    bar: f32,
}
Run

How can we define some default values? You can use Default:

#[derive(Default)]
struct SomeOptions {
    foo: i32,
    bar: f32,
}

fn main() {
    let options: SomeOptions = Default::default();
}
Run

Now, you get all of the default values. Rust implements Default for various primitives types.

If you want to override a particular option, but still retain the other defaults:

fn main() {
    let options = SomeOptions { foo: 42, ..Default::default() };
}
Run

Derivable

This trait can be used with #[derive] if all of the type’s fields implement Default. When derived, it will use the default value for each field’s type.

How can I implement Default?

Provide an implementation for the default() method that returns the value of your type that should be the default:

enum Kind {
    A,
    B,
    C,
}

impl Default for Kind {
    fn default() -> Self { Kind::A }
}
Run

Examples

#[derive(Default)]
struct SomeOptions {
    foo: i32,
    bar: f32,
}
Run

Required methods

Returns the “default value” for a type.

Default values are often some kind of initial value, identity value, or anything else that may make sense as a default.

Examples

Using built-in default values:

let i: i8 = Default::default();
let (x, y): (Option<String>, f64) = Default::default();
let (a, b, (c, d)): (i32, u32, (bool, bool)) = Default::default();
Run

Making your own:

enum Kind {
    A,
    B,
    C,
}

impl Default for Kind {
    fn default() -> Self { Kind::A }
}
Run

Implementors

impl Default for Global

impl<T: Default> Default for Box<T>

impl<T> Default for Box<[T]>

impl Default for Box<str>

impl<B: ?Sized> Default for Cow<'_, B> where
    B: ToOwned<Owned: Default>, 

impl<T: Ord> Default for BinaryHeap<T>

impl<K: Ord, V> Default for BTreeMap<K, V>

impl<T: Ord> Default for BTreeSet<T>

impl<T> Default for LinkedList<T>

impl<T> Default for VecDeque<T>

impl<T: Default> Default for Rc<T>

impl<T> Default for Weak<T>

impl Default for String

impl<T> Default for Weak<T>

impl<T: Default> Default for Arc<T>

impl<T> Default for Vec<T>

impl Default for Usercall

impl Default for Return

impl<T: Default> Default for Identified<T>

impl Default for Secs

impl Default for Tcs

impl Default for TcsFlags

impl Default for Pageinfo

impl Default for Secinfo

impl Default for Pcmd

impl Default for Report

impl Default for MeasEAdd