Skip to content

New lint: Unused temporary variable #5880

Open

Description

What it does

Lint should detect if we create a temporary variable that is dropped without usage (or side-effects).

See example below for creating a String which should have been assigned to the shadowed name, but instead does nothing.

Categories (optional)

  • Kind: clippy::correctness

What is the advantage of the recommended code over the original code

Original code creates a temporary String, which has the correct transformation applied but is then dropped, and the .len() is called on the original &str. This is not the intended behaviour but there are no warnings or errors.

The new code correctly assigns the temporary variable (to shadow the same username variable), which is then used.

The lint could just check the that variable is assigned and used later in the code.

Drawbacks

How can we distinguish if a method called on the temporary variable has side effects, and that is what was intended? Perhaps only apply for standard library types and methods.

Example

validate_with(|username: &str| -> Result<(), &str> {
                // Here String is immediately dropped
                username.to_string().retain(|c| !c.is_whitespace() && c.is_digit(10)); 
                if username.len() != 16 { // This erroneously checks against original &str
                    return Err("Mullvad account number should be 16 digits!");
                }
                Ok(())
            })

Could be written as:

validate_with(|username: &str| -> Result<(), &str> {
                // Now the temporary String is assigned and used
                let username = username.to_string().retain(|c| !c.is_whitespace() && c.is_digit(10)); 
                if username.len() != 16 { // Checks new String as intended
                    return Err("Mullvad account number should be 16 digits!");
                }
                Ok(())
            })
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Assignees

No one assigned

    Labels

    A-lintArea: New lintsE-hardCall for participation: This a hard problem and requires more experience or effort to work onL-correctnessLint: Belongs in the correctness lint group

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions