1

A common Go programming error we've seen is:

for _, item := range items {
    item.SomeField = value // oops
}

As range copies the value, assigning to the struct field effectively does nothing.

The correct way is to use the index: https://stackoverflow.com/a/16013949/161457

Is there a way to detect this error with golangci-lint? (If not, is there another linter that will catch this?)

3
  • 1
    golangci-lint has the linter ineffassign enabled by default. But this linter misses some cases because it does not consider any type information in its analysis. For example, assignments to struct fields are never marked as ineffectual. Also see this bug report: github.com/gordonklaus/ineffassign/issues/70. Commented May 12, 2023 at 23:33
  • Per the bug report, staticcheck might support it. I tried that tool with SA4005 - Field assignment that will never be observed and it did not catch it though. Commented May 15, 2023 at 19:59
  • 1
    I just checked the source code of staticcheck. According to the test cases, SA4005 is for checking field assignment in a method (that maybe a pointer receiver should be used instead). It's not for the use case shown in this question. Commented May 16, 2023 at 1:28

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.