Skip to content

needless_borrow false positive, with broken suggestion #8380

@ijackson

Description

@ijackson

To reproduce

Run cargo clippy with this in src/main.rs:

struct A { }

#[derive(Debug)]
struct B { }

impl From<&A> for B {
    fn from(_a: &A) -> B { B { } }
}

fn main() {
    let a = A { };
    
    // warning: this expression borrows a value the compiler would automatically borrow
    // 12 | let b: B = (&a).into();
    //                 ^^^^ help: change this to: `a`
    let b: B = (&a).into();
    
    // error[E0277]: the trait bound `B: std::convert::From<A>` is not satisfied
    // let b: B = a.into();
    
    println!("{:?}", &b)
}

Output with current nightly (bad)

    Checking foo v0.1.0 (/home/rustcargo/d/foo)
warning: this expression borrows a value the compiler would automatically borrow
  --> src/main.rs:16:16
   |
16 |     let b: B = (&a).into();
   |                ^^^^ help: change this to: `a`
   |
   = note: `#[warn(clippy::needless_borrow)]` on by default
   = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#needless_borrow

warning: `foo` (bin "foo") generated 1 warning
    Finished dev [unoptimized + debuginfo] target(s) in 0.18s

Discussion

The disagnostic is not correct. Changing the program as clippy suggests does not work (see comment in my example). Both nightly and stable reject the modified program.

Stable clippy IMO-rightly accepts the original program without complaint.

Meta

rustcargo@zealot:~/d/foo$ rustc +stable --version
rustc 1.58.1 (db9d1b20b 2022-01-20)
rustcargo@zealot:~/d/foo$ rustc +nightly --version
rustc 1.60.0-nightly (6abb6385b 2022-01-26)
rustcargo@zealot:~/d/foo$ 

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions