Search code examples
rust

Is there any difference between Rc::clone(&rc) and rc.clone() in Rust? Is there any compilation optimizations happen based on that?


I noticed the rust book recommends to use Rc::clone(&rc) over rc.clone() as follows:

use std::rc::Rc;

let five = Rc::new(5);

// recommended
let _ = Rc::clone(&five);

// not recommended
let _ = five.clone();

Why?


Solution

  • The function syntax (Rc::clone(&rc)) makes it clear you're only making a new shared reference (cheap), rather than cloning the underlying object being referenced (maybe expensive). For arbitrary reference counted types, it may not be clear if a shallow or deep copy is occurring.

    This issue with readability/clarity has led to proposals for a separate interface for cloning reference counted pointer types, with linters now warning when a reference counted type is cloned via a method.