I am using a #[derive(Clone)]
for struct<T>
where T
is not Clone
but all the elements of the struct are Clone
(since Rc<T>
is always Clone
). How, if at all, can I convince Rust to derive the trait for me?
A working example: (playground link)
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
}
The error message is
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`
This doc indicates that having Clone
members should be enough (and that would make sense), but maybe I am missing something.
I know I could implement Clone
myself, but since I already use WithRc<T>
as a thin wrapper around a Rc
-wrapped data structure where some methods need the shared pointer to self, I'm trying to avoid more boilerplate.