在下面的代码中,您可以看到我正在尝试克隆“
a:A
”,其中A
派生自Clone
。use std::sync::Arc;
pub trait S{}
struct B{
}
impl S for B{
}
#[derive(Clone)]
struct A<T: ?Sized>{
a: Arc<Box<T>>
}
fn main() {
let a: A<dyn S> = A{
a: Arc::new(Box::new(B{}))
};
a.clone();
}
然而我遇到了这个错误:
错误:
Compiling playground v0.0.1 (/playground)
error[E0599]: the method `clone` exists for struct `A<dyn S>`, but its trait bounds were not satisfied
--> src/main.rs:22:7
|
3 | pub trait S{}
| ----------- doesn't satisfy `dyn S: Clone`
...
13 | struct A<T: ?Sized>{
| -------------------
| |
| method `clone` not found for this
| doesn't satisfy `A<dyn S>: Clone`
...
22 | a.clone();
| ^^^^^ method cannot be called on `A<dyn S>` due to unsatisfied trait bounds
|
= note: the following trait bounds were not satisfied:
`dyn S: Clone`
which is required by `A<dyn S>: Clone`
= help: items from traits can only be used if the trait is implemented and in scope
= note: the following trait defines an item `clone`, perhaps you need to implement it:
candidate #1: `Clone`
对于任何的 T
,A
都应该实现 Clone
,因为在 A
上的克隆操作只需调用 A {a: old_a.clone()}
,并且由于它是一个 Arc
,所以它总是实现了clone方法。
因为 #[derive(Clone)]
的存在,理应保证 A
实现了 Clone
吗?
T
中去掉?Sized
,它仍然可以工作。 - Guerlando OCs