Why can't Vec<T> implement Default when T isn't Default

As the title says:

Why can't Vec<T> implement Default when T isn't Default? After all, it can return Vec::new() which is available for non-default types too.

Is there an implementation issue or something else?

It actually does implement Default for any T.

https://doc.rust-lang.org/std/vec/struct.Vec.html#impl-Default

Just hazarding a guess -- if you're try to derive(Default) on some struct Foo<T> containing a Vec<T>, the derivation will add that T: Default requirement. This happens just for being a type parameter, not because of the vector.

2 Likes

Oh. You're right. It's when I use #[derive(Default)] it doesn't implement it.

There's a long-standing issue on this point:

The last comment right now points to an alternative derive(SmartDefault) that you might like:
https://docs.rs/smart-default/0.6.0/smart_default/derive.SmartDefault.html

4 Likes

The derive(Default) macro is broken in that regard. All type parameters have to be Default for it to work, even when they aren't actually needed for construction.

4 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.