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

False positive with `map_clone`

Open Luk-ESC opened this issue 1 year ago • 1 comments

Summary

calling .map(|foo| U::clone(...)) on an Option<&T> or Iterator over &T incorrectly triggers the map_clone lint.

Notes:

  • It has to be a &T
  • U can be any type that implements Clone
  • It does not have to be .map(|foo| U::clone(&foo)), the lint will trigger no matter what value is put into U::clone (foo can be unused)
  • This affects both Options and Iterators.

Lint Name

map_clone

Reproducer

I tried this code:

fn main() {
    let x: Option<&u8> = None;
    let y = x.map(|x| String::clone(loop {}));
}

I saw this happen:

...
warning: you are explicitly cloning with `.map()`
 --> src/main.rs:3:13
  |
3 |     let y = x.map(|x| String::clone(loop {}));
  |             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: consider calling the dedicated `copied` method: `x.copied()`
  |
  = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#map_clone
  = note: `#[warn(clippy::map_clone)]` on by default
...

I expected to see this happen: map_clone not triggering.

The same issue appears with

fn main() {
    let x: Vec<&u8> = vec![];
    let y = x.into_iter().map(|x| String::clone(loop {}));
}

Version

rustc 1.78.0-nightly (6cc484351 2024-02-10)
binary: rustc
commit-hash: 6cc4843512d613f51ec81aba689180c31b0b28b6
commit-date: 2024-02-10
host: x86_64-unknown-linux-gnu
release: 1.78.0-nightly
LLVM version: 17.0.6

Additional Labels

@rustbot label +I-suggestion-causes-error

Luk-ESC avatar Feb 11 '24 03:02 Luk-ESC

I'm working on this

maekawatoshiki avatar Feb 12 '24 15:02 maekawatoshiki