Rust default - ..Default::default()

Expected - should-be:
Person { name: "sunface", age: 30, hobby: "test a hobby" }

As-Is - incorrect:
Person { name: "sunface", age: 30, hobby: "" }

// Fix the error
#[derive(Debug, Default)]
struct Person {
    name: String,
    age: u8,
    hobby: String,
}

impl Person {
    fn default() -> Person {
        Person {
            name: String::from("Test a person - name"),
            age: 0,
            hobby: String::from("test a hobby"),
        }
    }
}
fn main() {
    let age = 30;
    let p = Person {
        name: String::from("sunface"),
        age,
        ..Default::default()
    };

    println!("{:?}", p); // Person { name: "sunface", age: 30, hobby: "" }
    // I was expecting Person { name: "sunface", age: 30, hobby: "test a hobby" }
}

Remove Default here.

Should be: impl Default for Person {
You're implementing the Default trait.

Also see the example in the docs.
(I did not compile my changes.)

4 Likes

Note also that calling Person::default() instead of Default::default(), i.e. inherent function instead of trait one, will do the thing you expect. Yes, you can have different functions with the same name, if they are from the different sources (that is, at least one of them is from some trait, and another is from somewhere else).

3 Likes