Skip to content

False positive with map_clone  #12271

Closed
@Luk-ESC

Description

@Luk-ESC

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    C-bugCategory: Clippy is not doing the correct thingI-false-positiveIssue: The lint was triggered on code it shouldn't haveI-suggestion-causes-errorIssue: The suggestions provided by this Lint cause an ICE/error when applied

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions