Can't default initialize an Option in a generic struct


#1

Hi,

I am trying to make this code compile:

use std::default::Default;

#[derive(Default)]
struct Struct<T> {
    opt: Option<T>,
}

impl<T> Struct<T> {
    fn new() -> Struct<T> {
        Default::default()
    }
}

fn bare_new<T>() -> Option<T> {
    Default::default()
}

fn main() {
}

The bare_new method compiles, but the Struct::new method does not. I get the following error:

x.rs:10:9: 10:25 error: the trait `core::default::Default` is not implemented for the type `T` [E0277]

I don’t understand why the compiler expects T to implement the Default trait since Option already implement it. Even if the documentation does not say anything about it, I expect the default value to be None (and it probably is, because bare_new compiled successfully), so there is no need for T to implement that trait.

Any help is appreciated.


#2

The derive(Foo) feature isn’t very smart. It will only derive Foo for Struct<T> if T implements Foo, otherwise you’ll have impl<T> Foo for Struct<T> manually.


#3

This is caused by issue #26925.


#4

I see, thanks for the replies and the link! I’ll implement the trait manually then.