Skip to content

Detect looping over a map to compare its key exactly #1447

@gannett-ggreer

Description

@gannett-ggreer

Is your feature request related to a problem? Please describe.
In a recent code change, we modified a variable from a slice to a map:

-       TagIDs             []string
+       TagIDs             map[string]float64

but a loop across the now-map was changed in an obvious but inefficient way:

-       for _, id := range a.TagIDs {
+       for id := range a.TagIDs {
                if id == someStaticValue {
                        return nil
                }
        }

given that is now a map there's a really direct way to do that test.

Describe the solution you'd like
The linter should flag the loop or suggest a fix to make it:

if _, exists := a.TagIDs[someStaticValue]; exists {
    return nil
}

Describe alternatives you've considered
This isn't a correctness issue, just inefficiency, so when in doubt it shouldn't be too picky.

Additional context
This happens remarkably often in my experience for people new to Go or who are making scattered changes and don't always think too deeply about fixing the resulting compilation errors as they focus on the end goal. None of the golangci-lint linters or current version of revive tripped on that loop as anything of note, but it is also more of a learning opportunity for the programmer rather than anything wrong necessarily with the program.

Metadata

Metadata

Assignees

No one assigned

    Labels

    rule proposalIssue proposing a new rule

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions