Arc<T>是否应该为任何T实现Clone?

5
在下面的代码中,您可以看到我正在尝试克隆“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`

对于任何的 TA 都应该实现 Clone,因为在 A 上的克隆操作只需调用 A {a: old_a.clone()},并且由于它是一个 Arc,所以它总是实现了clone方法。

因为 #[derive(Clone)] 的存在,理应保证 A 实现了 Clone 吗?

1个回答

7
这是 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() }
  }
}

如果我从T中去掉?Sized,它仍然可以工作。 - Guerlando OCs

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