Rust: Providing a default implementation, how to use Default::default()

2020年11月23日 108点热度 0人点赞 0条评论
内容目录

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.

Usually, when processing structures that represent configurations, you are not concerned with certain values and just want to assign them a default value quietly.

Rust uses Default::default(); to assign a default value to a type, which is equivalent to C#'s default, default({type}).

Nearly every primitive type in Rust has a default value.

The usage of Default::default() is as follows:

    // There's a default value for nearly every primitive type
    let foo: i32 = Default::default();
    println!("foo: {}", foo); // Prints "foo: 0"

To set a default value for a struct, you need to use the #[derive(Default)] attribute.

#[derive(Default)]
struct PizzaConfig {
    wants_cheese: bool,
    number_of_olives: i32,
    special_message: String,
}

... ...

// A struct that derives from Default can be initialized like this
let pizza: PizzaConfig = Default::default();

// Prints "wants_cheese: false"
println!("wants_cheese: {}", pizza.wants_cheese);

// Prints "number_of_olives: 0"
println!("number_of_olives: {}", pizza.number_of_olives);

// Prints "special_message: "
println!("special message: {}", pizza.special_message);</code></pre>

Setting default values for structs

Rust enums need to implement the Default trait:

// You can implement default easily for your own types
enum CrustType {
    Thin,
    Thick,
}
impl Default for CrustType {
    fn default() -> CrustType {
        CrustType::Thin
    }
}
    let _enum: CrustType = Default::default();

痴者工良

高级程序员劝退师

文章评论