gpt4 book ai didi

rust - 使用 PhantomData 时不满足 trait bound `T: std::default::Default`

转载 作者:行者123 更新时间:2023-12-03 11:30:21 25 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





Deriving a trait results in unexpected compiler error, but the manual implementation works

(2 个回答)


1年前关闭。




在我当前的项目中,我正在尝试编写可以由这个最小示例表示的内容:

#[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 实现它又有什么关系呢? ?

最佳答案

查看来自@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()
};
}

关于rust - 使用 PhantomData<T> 时不满足 trait bound `T: std::default::Default`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59538071/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com