Default Values with derive(Default)
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
Default verbose=false
Default port=0
Default Config has host=localhost
Default Config has timeout=0
Default Config has retry=false
Algorithm Flow

Solution Approach
Best Answers
#[derive(Default)]
struct Config {
timeout: u32,
retry: bool,
host: String,
}
fn solution() -> u32 {
let c: Config = Default::default();
c.timeout
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
