Code Logo

Default Values with derive(Default)

Published at25 Jul 2026
Rust Traits & Generics Easy 0 views
Like0

Write a Rust function that defines a Config struct with fields like timeout: u32, retry: bool, and host: String, derives the Default trait, and returns the value of a specific field from the default instance. The Default trait provides a default() method that creates an instance with zero or empty values for all fields.

The #[derive(Default)] attribute generates an implementation of std::default::Default for a struct. For each field, it uses the default value of that type: 0 for numeric types, false for bool, String::new() for String, None for Option. This is useful for configuration structs where most fields have sensible defaults.

Default is one of the most practical standard library traits. It is used extensively throughout the Rust ecosystem: structopt/clap for command-line argument defaults, builder patterns with pre-populated defaults, and test fixtures with minimal setup.

Time complexity is O(1) for primitive fields, O(n) for heap-allocated fields like String. Space complexity is O(n) for the struct including any heap allocations. The derived implementation is efficient and automatically updated when fields are added or removed.

Edge cases include String fields defaulting to empty string, numeric fields defaulting to 0, bool fields defaulting to false, Option fields defaulting to None, and ensuring all field types implement Default for the derive to work.

Example Input & Output

Example 1
Input
()
Output
false
Explanation

Default verbose=false

Example 2
Input
()
Output
0
Explanation

Default port=0

Example 3
Input
()
Output
localhost
Explanation

Default Config has host=localhost

Example 4
Input
()
Output
0
Explanation

Default Config has timeout=0

Example 5
Input
()
Output
false
Explanation

Default Config has retry=false

Algorithm Flow

Recommendation Algorithm Flow for Default Values with derive(Default)
Recommendation Algorithm Flow for Default Values with derive(Default)

Solution Approach

#[derive(Default)]
struct Config {
    timeout: u32,
    retry: bool,
    host: String,
}

fn solution() -> u32 {
    let c: Config = Default::default();
    c.timeout
}

Best Answers

rust - Approach 1
#[derive(Default)]
struct Config {
    timeout: u32,
    retry: bool,
    host: String,
}

fn solution() -> u32 {
    let c: Config = Default::default();
    c.timeout
}