Skip to content

needless_borrow false positive: if and else have incompatible types #9739

Closed
@est31

Description

@est31

Summary

If you have a function accepting both a slice and an array, the needless_borrow lint suggests you to turn the slice into an array. Most times this works, but if you have an else/if with differently sized slices in the then/else bodies, applying the lint's suggestion causes a compilation error.

Lint Name

needless_borrow

Reproducer

I tried this code:

fn foo<D: std::fmt::Display>(_it: impl IntoIterator<Item = D>) {}

fn main() {
    foo(if std::env::var_os("HI").is_some()  {
        &[0]
    } else {
        &[] as &[u32]
    });
}

I saw this happen:

error: the borrowed expression implements the required traits
 --> a.rs:7:9
  |
7 |         &[0]
  |         ^^^^ help: change this to: `[0]`
  |
  = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#needless_borrow

Version

rustc 1.66.0-nightly (0da281b60 2022-10-27)

but also on

rustc 1.65.0-beta.4 (a31705549 2022-10-21)

(no idea about stable)

Additional Labels

No response

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