How to Add Default Values to a Struct in Rust

Add default values to Rust structs using the Default trait or derive macro for automatic initialization.

Use the #[derive(Default)] attribute on your struct to automatically generate default values for all fields that implement Default.

#[derive(Default)]
struct User {
    username: String,
    age: u32,
}

let user = User::default();

If your struct contains fields without a Default implementation, manually implement the Default trait to specify custom values.

struct User {
    username: String,
    age: u32,
}

impl Default for User {
    fn default() -> Self {
        Self {
            username: String::from("guest"),
            age: 0,
        }
    }
}

let user = User::default();

For structs with many fields, use the struct update syntax to set defaults for most fields while overriding specific ones.

let user = User {
    username: String::from("admin"),
    ..Default::default()
};