#[derive(Default, Debug)] struct Person { name: String, age: u32, } #[derive(Debug)] struct PersonWithCustomDefault { name: String, age: u32, } impl Default for PersonWithCustomDefault { fn default() -> Self { PersonWithCustomDefault { name: "Unknown".to_string(), age: 10 } } } fn main() { let person = Person::default(); println!("{:?}", person); // Output: Person { name: "", age: 0 } let person_with_custom_default = PersonWithCustomDefault::default(); println!("{:?}", person_with_custom_default); // Output: PersonWithCustomDefault { name: "Unknown", age: 10 } }
ποΈ #Rustlang Tip: Use the #[derive(Default)] attribute for struct initialization if all your fields have a Default implementation.
Be careful though, for Strings field, the default implementation will create an empty string!
#RustTricks #Rust30by30 #Day10