Open dhardy opened 6 months ago
Would be good to cover similar types also, from what I can see:
Option
Result
Cow
RefCell
cmp::Reverse
io::Cursor
Here's another example that makes assigning_clones
sad:
#[derive(Clone)]
struct Foo {
_x: u64,
}
#[derive(Clone)]
pub struct Wrapper {
value: Option<Foo>,
}
impl Wrapper {
pub fn update(&mut self, s: &Wrapper) {
self.value = s.value.clone();
}
}
results in
warning: assigning the result of `Clone::clone()` may be inefficient
--> src/lib.rs:20:9
|
20 | self.value = s.value.clone();
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: use `clone_from()`: `self.value.clone_from(&s.value)`
|
Similarly, Option<Arc>
complains in places where plain Arc
would not:
use std::sync::Arc;
struct Foo {
_x: u64,
}
#[derive(Clone)]
pub struct Wrapper {
value: Option<Arc<Foo>>,
}
impl Wrapper {
pub fn update(&mut self, s: &Wrapper) {
self.value = s.value.clone();
}
}
warning: assigning the result of `Clone::clone()` may be inefficient
--> src/lib.rs:26:9
|
26 | self.value = s.value.clone();
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: use `clone_from()`: `self.value.clone_from(&s.value)`
|
= help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#assigning_clones
= note: `#[warn(clippy::assigning_clones)]` on by default
Summary
Motivation
I have a type,
Id
, which is really cheap to copy, yet unfortunately cannot implementCopy
: it uses just au64
in-memory representation in almost all cases, and a reference-counted heap-allocated representation in the remaining cases. It also gets used quite frequently, and I want to make it easy to use and pass around. I mean, I'm almost tempted to let heap-allocated instances leak just so that I can implementCopy
.It's also common to want to copy an
Option<Id>
around. Queue Clippy'sassigning_clones
recommending usage ofclone_from
instead, despite the fact thatId
does not implementclone_from
(or have anything to gain if it did, since the heap-allocated representations are not mutable).Besides which, usages of
Id
are not particularly performance sensitive. Remember premature optimisation is the root of all evil? There may be cases where this lint significantly improves code, but it's not here.Expectation
Either that Clippy can recognise the false positive (
Option
implsclone_from
butT
doesn't) or that this lint can be disabled with an annotation on the type.Lint Name
assigning_clones
Reproducer
I tried this code:
I saw this happen:
I expected to see this happen: no warning.
Version
Additional Labels
No response