Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to clone an Option of Rc in Rust?

Tags:

clone

rust

Say I have an Option of Rc:

let x = Some(Rc::new(3));

If I need to make a clone, I can do:

let y = Some(Rc::clone(&x.unwrap()));

But it seems there's also a short cut:

let y = x.clone();

Are there any difference between these options? Or they are internally doing the same thing. Rust newbie here, thanks for any clarification.

like image 285
Psidom Avatar asked Nov 02 '19 20:11

Psidom


1 Answers

There's a generic implementation

impl<T: Clone> Clone for Option<T> {
    #[inline]
    fn clone(&self) -> Self {
        match self {
            Some(x) => Some(x.clone()),
            None => None,
        }
    }
    // ...
}

So if x is Option<Rc<T>>, x.clone() will simply defer to the Clone implementation on Rc<T>.

like image 132
SCappella Avatar answered Sep 30 '22 17:09

SCappella