使用PhantomData<T>时,未满足T: std::default::Default的特性限制。

5

在我当前的项目中,我正在尝试编写一些可由此最小示例所表示的内容:

#[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

对我而言,这有点奇怪,因为Default是从APhantomData<T>派生的,那么为什么如果它没有为B实现就会有影响呢?

1个回答

6

请查看@mcarton提供的链接,因为手动实现默认特质确实可以编译

//#[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()
    };
}

是的,这似乎正是 https://github.com/rust-lang/rfcs/pull/2353 所解决的问题。 - zbrojny120

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接