Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The trait bound `T: std::default::Default` is not satisfied when using PhantomData<T> [duplicate]

Tags:

rust

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?

like image 625
zbrojny120 Avatar asked Dec 30 '19 23:12

zbrojny120


1 Answers

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()
    };
}
like image 63
Nathan Jhaveri Avatar answered Nov 15 '22 08:11

Nathan Jhaveri