Default trait for sensible zero values
Marcus Chen
Jan 2026
1 tab
#[derive(Default, Debug)]
struct Config {
host: String,
port: u16,
debug: bool,
}
fn main() {
let config = Config {
port: 8080,
..Default::default()
};
println!("{:?}", config);
}
1 file · rust
Explain with highlit
The Default trait provides a default value for a type, useful for builder patterns, config merging, and initialization. I derive Default on structs where zero/empty is meaningful. For custom logic, implement it manually. Default::default() is the standard way to create an instance. It's especially useful with struct update syntax: Config { port: 8080, ..Default::default() }. For types like Vec, String, and Option, default is already implemented (empty vec, empty string, None). I use Default bounds in generic code when I need to create instances. It's a small convenience that makes APIs more ergonomic and composable.