rust

Is there a short way to implement Default for a struct that has a field that does not implement Default?


I have a struct that has 20 fields:

struct StructA {
    value1: i32,
    value2: i32,
    // ...
    value19: i32,
    day: chrono::NaiveDate,
}

I'd like to impl Default trait for StructA. I tried to add #[derive(Default)] to the struct, but chrono::NaiveDate doesn't implement Default.

I then tried to implement Default for StructA:

impl Default for StructA {
    fn default() -> Self {
        Self {
            value1: Default::default(),
            value2: Default::default(),
            // ...
            value19: Default::default(),
            day: chrono::NaiveDate::from_ymd(2021, 1, 1),
        }
    }
}

This code works fine, but the parts of value1 through value19 are redundant. Is there a solution with less code?


Solution

  • The derivative crate makes this kind of thing a breeze:

    #[derive(Derivative)]
    #[derivative(Default)]
    struct StructA {
        value1: i32,
        value2: i32,
        // ...
        value19: i32,
        #[derivative(Default(value = "NaiveDate::from_ymd(2021, 1, 1)"))]
        day: NaiveDate,
    }
    

    If you want to avoid external crates, your options are: