我使用#[derive(Clone)]
struct<T>
T
不是Clone
,但结构的所有元素都是Clone
(从{{1}开始总是Rc<T>
)。如果有的话,我能说服Rust为我找出这个特性吗?
一个工作示例:(playground link)
Clone
错误消息是
use std::rc::Rc;
struct NotClone;
#[derive(Clone)]
struct WithRc<T> {
elem: Rc<T>
// ...
}
impl<T> WithRc<T> {
pub fn new(v: T) -> WithRc<T> {
WithRc { elem: Rc::new(v) }
}
}
fn main() {
let a = WithRc::new(NotClone { });
let b = a.clone(); // This triggers the error
}
This doc表示拥有error: no method named `clone` found for type `WithRc<NotClone>` in the current scope
--> src/main.rs:19:15
|
19 | let b = a.clone(); // This triggers the error
| ^^^^^
|
= note: the method `clone` exists but the following trait bounds were not satisfied: `NotClone : std::clone::Clone`
= help: items from traits can only be used if the trait is implemented and in scope; the following trait defines an item `clone`, perhaps you need to implement it:
= help: candidate #1: `std::clone::Clone`
成员应该足够了(这是有意义的),但也许我错过了一些东西。
我知道我可以自己实现Clone
,但是因为我已经使用Clone
作为WithRc<T>
包装数据结构的瘦包装器,其中包含一些方法需要共享指针指向self,我试图避免更多的样板。