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:
With Default
, you can simply write:
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 true
max_users
(u32): Default value 100
auto_save
(bool): Default value true
cache_size_mb
(u32): Default value 512
log_level
(String): Default value "INFO"
retry_attempts
(u32): Default value 3
timeout_seconds
(u32): Default value 30
Your 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