Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

BC
BC

Posted on

     

Day38:Use default value - 100DayOfRust

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);}
Enter fullscreen modeExit fullscreen mode

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]
Enter fullscreen modeExit fullscreen mode

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Coder, Learner
  • Location
    New York
  • Joined

More fromBC

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp