rust-lang / rust-lang/rust-clippy

redundant_clone: false positive in equality comparison

Open
#5,700 8 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

C-bug I-false-positive I-suggestion-causes-error L-nursery S-needs-discussion
Dominant language
Rust
Stars
13.5k
Forks
2.2k
Avg merge
2d 10h
Merged PRs (30d)
32

Description

#[derive(PartialEq)]
struct Foo;

struct Bar;

impl ToOwned for Bar {
    type Owned = Foo;
    fn to_owned(&self) -> Foo {
        Foo {}
    }
}

impl std::borrow::Borrow<Bar> for Foo {
    fn borrow(&self) -> &Bar {
        static BAR: Bar = Bar {};
        &BAR
    }
}

fn main() {
    let f = Foo {};
    let b = Bar {};

    if f == b.to_owned() {
        println!("they match")
    }
}

(playground)

Note that there is no PartialEq implementation between Foo and Bar. This generates the following warning:

warning: redundant clone
  --> src/main.rs:24:14
   |
24 |     if f == b.to_owned() {
   |              ^^^^^^^^^^^ help: remove this
   |
   = note: `#[warn(clippy::redundant_clone)]` on by default
note: this value is dropped without further use
  --> src/main.rs:24:13
   |
24 |     if f == b.to_owned() {
   |             ^
   = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#redundant_clone

warning: 1 warning emitted

But applying the suggestion causes this error

error[E0308]: mismatched types
  --> src/main.rs:24:13
   |
24 |     if f == b {
   |             ^ expected struct `Foo`, found struct `Bar`

error: aborting due to previous error

For more information about this error, try `rustc --explain E0308`.

(playground)

Clippy version: 0.0.212

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Reproduce the redundant_clone warning with the Rust example in the issue, then inspect the redundant_clone lint and its suggestion logic. Add a regression test for the equality comparison and verify that the suggested change still compiles without changing the operand type.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
tooling
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.