Closed
Description
Summary
assigning_clones suggests code that fails to compile when the original code has deref.
Mentioning @Kobzol, who implemented this lint in #12077.
Reproducer
I tried this code:
#![allow(dead_code)]
#![warn(clippy::assigning_clones)]
use std::task::{Context, Waker};
fn f(mut prev: Box<Waker>, cx: &mut Context<'_>) -> Box<Waker> {
*prev = cx.waker().clone();
prev
}
I expected to see this happen: lint suggests code that can compile
Instead, this happened:
warning: assigning the result of `Clone::clone()` may be inefficient
--> src/lib.rs:7:5
|
7 | *prev = cx.waker().clone();
| ^^^^^^^^^^^^^^^^^^^^^^^^^^ help: use `clone_from()`: `prev.clone_from(cx.waker())`
|
= help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#assigning_clones
Suggested code prev.clone_from(cx.waker())
fails to compile because deref (*prev
) is dropped:
#![allow(dead_code)]
#![warn(clippy::assigning_clones)]
use std::task::{Context, Waker};
fn f(mut prev: Box<Waker>, cx: &mut Context<'_>) -> Box<Waker> {
prev.clone_from(cx.waker());
prev
}
error[E0308]: mismatched types
--> src/lib.rs:7:21
|
7 | prev.clone_from(cx.waker());
| ---------- ^^^^^^^^^^ expected `&Box<Waker>`, found `&Waker`
| |
| arguments to this method are incorrect
|
= note: expected reference `&std::boxed::Box<std::task::Waker>`
found reference `&std::task::Waker`
The correct code is (*prev).clone_from(cx.waker());
(preserve deref).
#![allow(dead_code)]
#![warn(clippy::assigning_clones)]
use std::task::{Context, Waker};
fn f(mut prev: Box<Waker>, cx: &mut Context<'_>) -> Box<Waker> {
(*prev).clone_from(cx.waker());
prev
}
Version
rustc 1.78.0-nightly (9c3ad802d 2024-03-07)
binary: rustc
commit-hash: 9c3ad802d9b9633d60d3a74668eb1be819212d34
commit-date: 2024-03-07
host: aarch64-apple-darwin
release: 1.78.0-nightly
LLVM version: 18.1.0
Additional Labels
@rustbot label +I-suggestion-causes-error