Arc<T>不应该为任何T实现Clone吗?

在下面的代码,你可以看到,我试图克隆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`

不应该为 anyA实现,因为克隆只会调用which 因为它总是实现克隆?CloneTAA {a: old_a.clone()}Arc

不应该保证A实现,Clone因为#[derive(Clone)]

回答

这是克隆的派生宏的实现问题。它不适用于包含不实现克隆自身的泛型类型的结构:https : //github.com/rust-lang/rust/issues/41481

在这种情况下,您必须Clone手动实施,正如您所说,这非常容易。

impl<T> Clone for A<T> {
  fn clone(&self) -> A<T> {
    A { a: self.a.clone() }
  }
}


以上是Arc&lt;T&gt;不应该为任何T实现Clone吗?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>