We can use Default::default
to give variable a default value.
Example:
use std::fmt;
enum CrustType {
Thin,
Thick
}
impl Default for CrustType {
fn default() -> CrustType {
CrustType::Thin
}
}
#[derive(Default)]
struct PizzaConfig {
has_cheese: bool,
num_of_olive: i32,
special_msg: String,
crust_type: CrustType
}
impl fmt::Display for PizzaConfig {
fn fmt(&self, f:&mut fmt::Formatter) -> fmt::Result {
let crust_type = match self.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)
}
}
fn main() {
let order: i32 = Default::default();
println!("Order: {}", order);
let pizza: PizzaConfig = Default::default();
println!("{}", pizza);
let cheese_pizza = PizzaConfig {
has_cheese: true,
num_of_olive: 10,
..Default::default()
};
println!("{}", cheese_pizza);
let delux_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 the default
method for self-defined enum type
3, Use derive(Default)
to give our struct some default value (integer is 0, boolean is false, string is empty string, enum type will choose the what default
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: 0
Pizza: [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)