Consider the following golang code:
for _, obj := range slice {
obj.Field = ...
}
The expectation is that in a loop we are changing Field
of all elements in the slice. But the reality is that slice will be unchanged at the end of the loop because in each iteration obj
is a shallow copy of slice[i]
. The correct implementation would be
for i := range slice {
obj := &slice[i]
obj.Field = ...
}
This bug seems very subtle which may escape code reviews as well. Even worse, if the object is a nested struct having some pointer fields than updates to some of the pointer fields may succeed (as it is a shallow copy only). I am looking for a linter, if any, that is capable enough of detecting this code pattern, and flag it as a potential bug to me.