The Default trait is a powerful tool for reducing code repetition and managing complex configurations. When dealing with structs that have many fields, manually specifying every value can be tedious and error-prone. The Default trait, combined with the ..Default::default() syntax, provides an elegant solution to this problem.
Consider a scenario where you have a configuration struct with 8 fields, but you only want to customize 1 or 2 of them. Without Default, you would need to write:
let config = AppConfig {
theme: String::from("Dark"),
notifications_enabled: true,
max_users: 100,
auto_save: true,
cache_size_mb: 512,
log_level: String::from("INFO"),
retry_attempts: 3,
timeout_seconds: 30,
};With Default, you can simply write:
let config = AppConfig {
theme: String::from("Dark"),
..Default::default()
};This not only reduces code repetition but also makes your code more maintainable and less prone to errors.
In this challenge, you will implement the Default trait for an AppConfig struct that has several configuration options. The struct should have the following fields and default values:
theme (String): Default value "Light"notifications_enabled (bool): Default value truemax_users (u32): Default value 100auto_save (bool): Default value truecache_size_mb (u32): Default value 512log_level (String): Default value "INFO"retry_attempts (u32): Default value 3timeout_seconds (u32): Default value 30Your task is to:
AppConfig struct with all specified fieldsDefault trait manuallyString::from() for string values in the default implementation..Default::default() must come last in struct initialization