History of the question:
Rust adheres to the philosophy of explicit initialization. For some standard collections and generic types, it is often required to have a "default" value. However, for complex structures, it is often ambiguous how to create them without parameters. For this purpose, the Default trait is introduced, which provides a standard constructor.
The problem:
To write universal containers and algorithms where a default value is sometimes expected (e.g., in Option::unwrap_or_default, Vec::resize), a mechanism for creating an instance without passing arguments is needed. But not all types are suitable for such a constructor; sometimes the default value may be non-obvious and dangerous.
The solution:
default() method that returns some instance (usually "empty", zeroed, or with preconditions).Code example:
#[derive(Default, Debug)] struct Config { retries: u32, verbose: bool, } fn main() { let cfg = Config::default(); println!("{:?}", cfg); }
Key features:
Will Default::default be forcibly called for Option<T> if T: Default?
No, Option does not automatically call default for T; unwrap_or_default is explicitly called.
Can default parameters be set through the Default trait in the structure constructor?
No, Default creates the entire structure as a whole; individual default fields cannot be substituted with regular constructor syntax.
Can derive(Default) break for a structure with fields that do not implement Default?
Yes, derive(Default) only works if all fields of the structure implement Default.
Config with Default, where the server port is 0 (an invalid default value). The program unexpectedly runs on the wrong port.
Pros:
Cons:
Default for a configuration structure with safe, consensus values (retries=3, verbose=false).
Pros:
Cons: