Cloning interior of a Rc


#1
  1. We have the following:

#[derive(Clone)]
pub struct Foo {};

pub fn magic(rc_foo: &Rc<Foo>) -> Foo {
    let t = rc_foo.clone(); // has type Rc<Foo>
    // Is there a way to clone the Foo ?
}
  1. Note that Foo derives Clone. From this, it seems that if we have a Rc object, we should be able to clone it and get a Foo object. How can we do that?

Thanks!


#2

Rc implements Deref, so you can dereference an Rc<Foo> to get a &Foo. Since you have a &Rc<Foo> here, you need to do two derefs:

let t: Foo = (**rc_foo).clone();

#3

Thanks! I figured out my mental mistake:

de-reffing a & or a &mut is fine. de-reffing does NOT consume the vaule. It’s only when we move that it gets consumed.

Thus, its’ fine to de-ref and clone the de-ref-ed value.


#4

You can also do Foo::clone(&rc_foo), this works due to deref coercions.