How to do it...

  1. In the src/bin folder, create a file called default.rs

  2. 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 }
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.219.64.172