0

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.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
  • 2
    *How, if at all, can I convince Rust to derive the trait for me?* — you cannot. – Shepmaster Mar 11 '17 at 22:08
  • @Shepmaster Thanks for the pointer to the other question. I must have missed it as it does not mention Clone in the name (but is Clone-specific). – Tomáš Gavenčiak Mar 11 '17 at 22:17
  • The code in the question uses `Clone`, but the problem is due to using `derive`. Any parameterized type will have that issue with any derived trait. – Shepmaster Mar 11 '17 at 22:19

0 Answers0