使用PhantomData <T>时,不满足特征绑定`T:std :: default :: Default`

时间:2019-12-30 23:50:33

标签: rust

我是我当前的项目,我试图写一些可以用这个最小示例表示的东西:

...
SliverFillRemaining(
  child: SliverToBoxAdapter(
    child: Container(
      decoration: BoxDecoration(
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(36),
          topRight: Radius.circular(36),
        ),
      ),
      child: SliverPadding(
        padding: const EdgeInsets.all(16),
        sliver: SliverFixedExtentList(
          itemExtent: 50.0,
          delegate: SliverChildBuilderDelegate(
            (BuildContext context, int index) {
              return Container(
                alignment: Alignment.center,
                color: Colors.lightBlue[100 * (index % 9)],
                child: Text('List Item $index'),
              );
            },
          ),
        ),
      ),
    ),
  ),
),
...

但是,此代码无法编译。

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

struct B;

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

对我来说,这有点奇怪,因为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 是为DefaultA派生的,所以如果没有为PhantomData<T>实现,那又为什么重要?

1 个答案:

答案 0 :(得分:2)

从{mcarton}中检出链接,因为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()
    };
}