Skip to content

Superfluous assignment does not give warning #75356

Description

@alvinhochun

This code (playground):

#[derive(Clone, Copy, Debug)]
struct Boo {
    b: i32,
}

fn main() {
    let mut a = 1i32;
    dbg!(a);
    // Warn?
    a = a;
    dbg!(a);

    let mut boo = Boo { b: 1 };
    dbg!(boo);
    // Warn?
    boo.b = boo.b;
    dbg!(boo);
}

contains superfluous self-assignments (a = a and boo.b = boo.b). These assignments are useless (especially so in Rust since assignment operations cannot be overloaded) and almost always means incorrect code.

However, rustc does not give a warning at all. Even clippy doesn't.

This broken code for example went unnoticed for years: https://github.com/PistonDevelopers/conrod/pull/1377/files

Examples in other compilers/linters:

Clang gives warning: explicitly assigning value of variable of type 'int' to itself [-Wself-assign] on variable self-assignment. It does not, however, warn about struct field self-assignment. GCC gives no warnings whatsoever. (Compiler Explorer)

go vet gives a warning self-assignment of [*] to [*] on variable and struct field self-assignmet.

eslint has the lint no-self-assign which works for both variables and object properties.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-lintsArea: Lints (warnings about flaws in source code) such as unused_mut.C-enhancementCategory: An issue proposing an enhancement or a PR with one.L-dead_codeLint: dead_codeT-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