Is this normal behaviour (Default::default())?


#1

Let’s say we’ve got two structs:

#[derive(Default)]
struct Quux {
    a: i32,
    b: i32,
}

#[derive(Default)]
struct Foo {
    x: Quux,
    y: Quux,
    z: Quux,
}

… With a Drop implementation:

impl Drop for Quux {
    fn drop(&mut self) {
        println!("Dropping")
    }
}

Now, when I create a new object like this:

println!("Creating");
let q = Foo {
    x: Quux { a: 0, b: 0 },
    .. Default::default()
};
println!("Created");

I get this output:

Creating
Dropping // this isn't good
Created
Dropping
Dropping
Dropping

So I realized that when the Foo is created, first default is called to it, then the field x is destroyed, so that the instance of another Quux is created and kept to it.

My question is: how can I avoid this? I don’t want that field to be created twice. Second: is this a normal thing? Should it go this way?

Third: Why have they choose to do it like so? I mean, instead of returning the whole created struct from Default::default(), it should create only what is needed, so that I don’t get things duplicated.


#2

This seems like expected behaviour to me. Default::default and record
update syntax isn’t magic. The former is just some function call, and the
second takes another instance and merges its fields in.

I wouldn’t expect anything else to work. The way to avoid this is… don’t
use this sugar. Sorry, but that’s it.