rust-clippy icon indicating copy to clipboard operation
rust-clippy copied to clipboard

Use of a = b.clone() instead of a.clone_from(&b)

Open laralove143 opened this issue 1 year ago • 4 comments

What it does

Catches the places where clone_from could be used instead

Lint Name

clone_from_candidate

Category

pedantic

Advantage

From the docs

  • a.clone_from(&b) is equivalent to a = b.clone() in functionality, but can be overridden to reuse the resources of a to avoid unnecessary allocations.

Drawbacks

I can't think of any

Example

let mut a = "a".to_owned();
let b = "b".to_owned();
a = b.clone();
drop(b);

Could be written as:

let mut a = "a".to_owned();
let b = "b".to_owned();
a.clone_from(&b);
drop(b);

laralove143 avatar Sep 21 '22 23:09 laralove143

the snippet of code provided doesn't exactly work, but using b.clone_into(&mut a); instead of a.clone_from(b); does.

danielrab avatar Sep 21 '22 23:09 danielrab

It would be good if the lint could check if the type has a provided fn clone_from, if it's using the default from Clone the suggestion wouldn't change anything

Alexendoo avatar Sep 22 '22 10:09 Alexendoo

the snippet of code provided doesn't exactly work, but using b.clone_into(&mut a); instead of a.clone_from(b); does.

Fixed it

laralove143 avatar Sep 22 '22 18:09 laralove143

It would be good if the lint could check if the type has a provided fn clone_from, if it's using the default from Clone the suggestion wouldn't change anything

There's no downsides to it and an upside so I'd say this is always more preferable

laralove143 avatar Sep 22 '22 18:09 laralove143