5

In my current project, I am trying to write something that can be represented by this minimal example:

#[derive(Default)]
struct A<T> {
    field: std::marker::PhantomData<T>
}

struct B;

fn main() {
    let a = A::<B> {
        ..Default::default()
    };
}

However, this code does not compile.

error[E0277]: the trait bound `B: std::default::Default` is not satisfied
  --> src/main.rs:10:11
   |
10 |         ..Default::default()
   |           ^^^^^^^^^^^^^^^^ the trait `std::default::Default` is not implemented for `B`
   |
   = note: required because of the requirements on the impl of `std::default::Default` for `A<B>`
   = note: required by `std::default::Default::default`

error: aborting due to previous error

Which for me, is a little bit strange, as Default is derived for A and for PhantomData<T>, so why does it matter if it's not implemented for B?

zbrojny120
  • 776
  • 6
  • 10

1 Answers1

6

Checkout the link from @mcarton, because manually implementing the default trait does compile.

//#[derive(Default)]
struct A<T> {
    field: std::marker::PhantomData<T>
}

struct B;

impl<T> Default for A<T> {
    fn default() -> Self {
        Self { field: Default::default() }
    }
}

fn main() {
    let a = A::<B> {
         ..Default::default()
    };
}
Nathan Jhaveri
  • 1,834
  • 1
  • 15
  • 17