Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

rust

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?

like image 578
rousan Avatar asked Oct 27 '22 22:10

rousan


1 Answers

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.

like image 194
ShadowRanger Avatar answered Nov 24 '22 00:11

ShadowRanger