Skip to content

Suggest removing let when unused variable shadows another variable #84664

Open
@meithecatte

Description

@meithecatte

Inspiration: this StackOverflow post

Given the following code:

fn largest<T>(list: &[T]) -> &T
    where T: PartialOrd + Copy
{
    let largest = &list[0];

    for item in list.iter() {
        if item > largest {
            let largest = item;
        }
    }

    largest
}

The current output is:

warning: unused variable: `largest`
 --> src/main.rs:8:17
  |
8 |             let largest = item;
  |                 ^^^^^^^ help: if this is intentional, prefix it with an underscore: `_largest`
  |
  = note: `#[warn(unused_variables)]` on by default

Ideally the output should look like:

warning: unused variable: `largest`
 --> src/main.rs:8:17
  |
8 |             let largest = item;
  |                 ^^^^^^^
...
4 |    let largest = &list[0];
  |        ------- note: variable with the same name defined here
...
8 |             let largest = item;
  |             ^^^ help: remove this `let` to assign instead of creating a new variable
  |
  = note: `#[warn(unused_variables)]` on by default

Some discussion on how to implement this on Zulip.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-control-flowArea: Control flowA-diagnosticsArea: Messages for errors, warnings, and lintsA-lintsArea: Lints (warnings about flaws in source code) such as unused_mut.A-resolveArea: Name/path resolution done by `rustc_resolve` specificallyC-enhancementCategory: An issue proposing an enhancement or a PR with one.T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions