Default trait in Rust

Metadata
aliases: []
shorthands: {}
created: 2022-06-17 16:01:33
modified: 2022-06-17 16:15:36

The Default trait is a trait in Rust, that allows us to implement a default value for a struct or enum.

pub trait Default {
    fn default() -> Self;
}

Examples

Example1

Let's say we want to implement a 2D point struct and the default value shall be , the zero length vector. Let's define the struct like this:

struct Vec2D {
    x: f64,
    y: f64,
}

And the implementation for Default will be:

impl Default for Vec2D {
    fn default() -> Self {
        x: 0.0,
        y: 0.0,
    }
}

Example2

We can also derive the Default trait using a macro if all of the member types also implement it. For example:

#[derive(Default)]
struct SomeStruct {
    a: i32,
    b: i32,
}

Now the default value for SomeStruct will be SomeStruct { a: i32::default(), b: i32::default() }.

Example3

The Default trait can of course also be implemented for an enum:

enum SomeThing {
    A,
    B,
    C,
}

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