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?)

Zeke Lu
  • 6,349
  • 1
  • 17
  • 23
TrueWill
  • 25,132
  • 10
  • 101
  • 150
  • 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: https://github.com/gordonklaus/ineffassign/issues/70. – Zeke Lu May 12 '23 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. – TrueWill May 15 '23 at 19:59
  • 1
    I just checked the source code of staticcheck. According to the [test cases](https://github.com/dominikh/go-tools/blob/bc668a17ee05a79bb9fdc320018de7503f0d9646/staticcheck/testdata/src/example.com/CheckIneffectiveFieldAssignments/CheckIneffectiveFieldAssignments.go), 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. – Zeke Lu May 16 '23 at 01:28

0 Answers0