Course contentsShow
← Rust
Lesson 50 of 1,9101. Rust Fundamentals and ToolingFree lesson

Implementing Default Behavior

Use trait defaults to simplify the construction and manipulation of custom types.

In this lesson, you will learn how to use the Default trait to provide sensible starting values for your custom types, making them easier to initialize.

Why use Default?

When you define a custom struct, you often have a "standard" version of that data in mind. For example, a Settings struct might have a default volume of 50 and a default theme of "Light." Instead of manually typing out every field every time you create an instance, you can use the Default trait to define what a "standard" instance looks like.

Implementing the Trait

To provide default behavior, you implement the Default trait for your struct. This requires defining a single function called default().

struct GameSettings {
    volume: u8,
    is_muted: bool,
}

impl Default for GameSettings {
    fn default() -> Self {
        Self {
            volume: 50,
            is_muted: false,
        }
    }
}

fn main() {
    // You can now create the struct using the default() function
    let settings = GameSettings::default();
    
    println!("Volume is {}", settings.volume);
}

Simplifying Construction

Once you implement Default, you can also use the "struct update syntax" to create modified versions of your default object. This is incredibly helpful when a struct has many fields, but you only want to change one or two:

let quiet_settings = GameSettings {
    volume: 10,
    ..GameSettings::default() // Fill in all other fields with defaults
};

In this snippet, we set volume to 10, and the ..GameSettings::default() syntax tells Rust to use the default value for every other field (in this case, is_muted becomes false).

This pattern makes your code cleaner and significantly reduces the boilerplate required to initialize complex data structures. By adhering to the Default trait, you enable other developers—and yourself—to construct your types with minimal effort while ensuring that every instance starts in a valid, predictable state.

Key Takeaway: Implementing the Default trait allows you to define a standard initialization state for your types, significantly simplifying code through the use of the default() constructor and struct update syntax.