We can useDefault::default
to give variable a default value.
Example:
usestd::fmt;enumCrustType{Thin,Thick}implDefaultforCrustType{fndefault()->CrustType{CrustType::Thin}}#[derive(Default)]structPizzaConfig{has_cheese:bool,num_of_olive:i32,special_msg:String,crust_type:CrustType}implfmt::DisplayforPizzaConfig{fnfmt(&self,f:&mutfmt::Formatter)->fmt::Result{letcrust_type=matchself.crust_type{CrustType::Thin=>"Thin",CrustType::Thick=>"Thick"};write!(f,"Pizza: [cheese: {}] [number of olive: {}] [msg: {}] [Crust: {}]",self.has_cheese,self.num_of_olive,self.special_msg,crust_type)}}fnmain(){letorder:i32=Default::default();println!("Order: {}",order);letpizza:PizzaConfig=Default::default();println!("{}",pizza);letcheese_pizza=PizzaConfig{has_cheese:true,num_of_olive:10,..Default::default()};println!("{}",cheese_pizza);letdelux_pizza=PizzaConfig{has_cheese:true,num_of_olive:10,special_msg:"Happy Birthday".to_string(),crust_type:CrustType::Thick,};println!("{}",delux_pizza);}
Here we use default values for 4 cases:
1, Assign an i32 value a default value, which is 0
2, Implement thedefault
method for self-defined enum type
3, Usederive(Default)
to give our struct some default value (integer is 0, boolean is false, string is empty string, enum type will choose the whatdefault
method returned)
4, When define our struct instance, after specify some value for some fields, for the rest fields, we can use..Default::default()
to give them default values.
Run:
Order: 0Pizza: [cheese: false] [number of olive: 0] [msg: ] [Crust: Thin]Pizza: [cheese: true] [number of olive: 10] [msg: ] [Crust: Thin]Pizza: [cheese: true] [number of olive: 10] [msg: Happy Birthday] [Crust: Thick]
Top comments(0)
Subscribe
For further actions, you may consider blocking this person and/orreporting abuse