9.4 Default Values and the Default Trait
Often, it’s useful to create a struct instance with default values. Rust provides the Default trait for this.
9.4.1 Deriving Default
If all fields in a struct themselves implement Default, you can derive Default for your struct.
#[derive(Default, Debug)]
struct AppConfig {
server_address: String, // Default is ""
port: u16, // Default is 0
timeout_ms: u32, // Default is 0
}
fn main() {
let config: AppConfig = Default::default();
// Or let config = AppConfig::default();
println!("Default config: {:?}", config);
// Output: AppConfig { server_address: "", port: 0, timeout_ms: 0 }
// Combine with struct update syntax
let custom_config = AppConfig {
port: 8080,
..Default::default() // Use defaults for other fields
};
println!("Custom config: {:?}", custom_config);
// Output: AppConfig { server_address: "", port: 8080, timeout_ms: 0 }
}
9.4.2 Implementing Default Manually
If deriving isn’t suitable, implement Default manually.
struct ConnectionSettings {
retries: u8,
use_tls: bool,
}
impl Default for ConnectionSettings {
fn default() -> Self {
ConnectionSettings {
retries: 3, // Custom default
use_tls: true, // Custom default
}
}
}
fn main() {
let settings = ConnectionSettings::default();
println!("Default retries: {}", settings.retries); // 3
}