- 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 ?
}
- 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!
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();
1 Like
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.
1 Like
You can also do Foo::clone(&rc_foo)
, this works due to deref coercions.
2 Likes