Search code examples
rustclone

How to clone an Option<Rc<_>> in 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?


Solution

  • 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>.