`Default` for Structs including `Vec<!Default>`

It doesn't seem one can derive(Default) (successfully) for structs which include a Vec of non-Default elements.
And it seems this should work, as Vec has a natural default (the empty vector) for any element type.

Playground:
https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=08fa3552aabe985f4577f877e10d7e87

// `derive(Default)` compiles
#[derive(Default)]
pub struct Stuff<T> {
    stuff: Vec<T>,
}

// But adding a blanket impl over `T` fails
impl<T> Stuff<T> {
    pub fn new() -> Self {
        Self::default()
    }
}

Rooting around GitHub issues, is this #[derive] sometimes uses incorrect bounds · Issue #26925 · rust-lang/rust · GitHub?

1 Like

It’s a known issue. Per the comments on the GitHub issue you found, derivative seems to be one of the recommended workarounds. I usually just manually implement Default to work around the issue.

2 Likes

As you've probably seen in the issues, this is an intentional choice because the goal is that field details -- especially when they're private -- shouldn't change this.

It would be possible for the derive to emit where Vec<T>: Default instead of where T: Default, but that's not what it does.

3 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.