# Module std::default [−] [src]

The `Default` trait for types which may have meaningful default values.

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 `struct`s that define a set of options:

fn main() { #[allow(dead_code)] struct SomeOptions { foo: i32, bar: f32, } }

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

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

#[allow(dead_code)] #[derive(Default)] struct SomeOptions { foo: i32, bar: f32, } fn main() { let options: SomeOptions = Default::default(); }

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

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

Now, you get all of the default values. Rust implements `Default` for various primitives types. If you have your own type, you need to implement `Default` yourself:

#![allow(dead_code)] enum Kind { A, B, C, } impl Default for Kind { fn default() -> Kind { Kind::A } } #[derive(Default)] struct SomeOptions { foo: i32, bar: f32, baz: Kind, } fn main() { let options: SomeOptions = Default::default(); }

    enum Kind {
        A,
        B,
        C,
    }

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

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

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

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

#[allow(dead_code)] #[derive(Default)] struct SomeOptions { foo: i32, bar: f32, } fn main() { let options = SomeOptions { foo: 42, ..Default::default() }; }

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

## Traits

Default | A trait for giving a type a useful default value.

# Help

## Keyboard Shortcuts

?
  Show this help dialog
S
  Focus the search field
⇤
  Move up in search results
⇥
  Move down in search results
⏎
  Go to active search result

## Search Tricks

Prefix searches with a type followed by a colon (e.g. `fn:`) to restrict the search to a given type.

Accepted types are: `fn`, `mod`, `struct`, `enum`, `trait`, `type`, `macro`, and `const`.

Search functions by type signature (e.g. `vec -> usize` or `* -> vec`)