When defining a struct or enum, sometimes derive(Default)
is not usable or not as smart as one would like. E.g:
#[derive(Default)]
pub struct Foo<T>(Vec<T>);
In this example, Foo<T>
will only implement Default
if T
does, which is a shame because Vec<T>
implements defaults regardless (as it produces an empty vec).
In such cases, I end up defining a new()
method and implementing Default::default()
manually, one of these implementations relying on the other, e.g.
pub struct Foo<T>(Vec<T>);
impl<T> Foo<T> {
pub fn new() -> Self {
Foo(vec![])
}
}
impl<T> Default for Foo<T> {
fn default() -> Self {
Self::new()
}
}
That's a little too much boilerplate to my taste. It would be nice to have a derive macro that generated the impl<T> Default ...
block whenever an new()
method with no parameter existed. I could therefore write:
#[derive(DefaultNew)]
pub struct Foo<T>(Vec<T>);
impl<T> Foo<T> {
pub fn new() -> Self {
Foo(vec![])
}
}
Does this make sense to anyone other than me? Is there already a crate providing such a macro?
PS: arguably, my example above could be handled by derive(Default)
and maybe it will eventually. But I believe there will always be cases where the implementation needs to be done manually, and therefore where the DefaultNew
derive macro could be useful.