Providing a default implementation
Often, when dealing with structures that represent configurations, you don't care about certain values and just want to silently assign them a standard value.
How to do it...
In the
src/bin
folder, create a file calleddefault.rs
Add the following code and run it with
cargo run --bin default
:
1 fn main() { 2 // There's a default value for nearly every primitive type 3 let foo: i32 = Default::default(); 4 println!("foo: {}", foo); // Prints "foo: 0" 5 6 7 // A struct that derives from Default can be initialized like this 8 let pizza: PizzaConfig = Default::default(); 9 // Prints "wants_cheese: false 10 println!("wants_cheese: {}", pizza.wants_cheese); 11 12 // Prints "number_of_olives: 0" 13 println!("number_of_olives: {}", pizza.number_of_olives); 14 15 // Prints "special_message: " 16 println!("special message: {}", pizza.special_message); 17 18 let crust_type = match pizza.crust_type { 19 CrustType::Thin => "Nice and thin", 20 CrustType::Thick => "Extra thick and extra filling", 21 }; 22 // Prints "crust_type: Nice and thin" 23 println!("crust_type: {}", crust_type); 24 25 26 // You can also configure only certain values 27 let custom_pizza = PizzaConfig { 28 number_of_olives: 12, 29 ..Default::default() 30 }; 31 32 // You can define as many values as you want 33 let deluxe_custom_pizza = PizzaConfig { 34 number_of_olives: 12, 35 wants_cheese: true, 36 special_message: "Will you marry me?".to_string(), 37 ..Default::default() 38 }; 39 40 } 41 42 #[derive(Default)] 43 struct PizzaConfig { 44 wants_cheese: bool, 45 number_of_olives: i32, 46 special_message: String, 47 crust_type: CrustType, 48 } 49 50 // You can implement default easily for your own types 51 enum CrustType { 52 Thin, 53 Thick, 54 } 55 impl Default for CrustType { 56 fn default() -> CrustType { 57 CrustType::Thin 58 } 59 }
How it works...
Nearly every type in Rust has a Default
implementation. When you define your own struct
that only contains elements that already have a Default
, you have the option to derive from Default
as well [42]. In the case of enums or complex structs, you can easily write your own implementation of Default
instead [55], as there's only one method you have to provide. After this, the struct
returned by Default::default()
is implicitly inferrable as yours, if you tell the compiler what your type actually is. This is why in line [3] we have to write foo: i32
, or else Rust wouldn't know what type the default object actually should become.
If you only want to specify some elements and leave the others at the default, you can use the syntax in line [29]. Keep in mind that you can configure and skip as many values as you want, as shown in lines [33 to 37].