8 ms·
What exactly is the difference here? Is the `x` variable being updated in the second sample so that the stored references all point to the same item?
by Measter 6y ago
What exactly is the difference here? Is the `x` variable being updated in the second sample so that the stored references all point to the same item?
- deleted 6y ago[deleted]
- simiones 6y agoYes, that code is equivalent to xrefs := []*struct{field1 int}{} var x struct{field1 int} for i := range longArrayName { x = longArrayName[i] //overwrite x with the copy x.field = value //modify the copy in x xrefs = append(xrefs, &x) //&x has the same value regardless of i } The desired refactoring would have been to this: xrefs := []*struct{field1 int}{} for i := range longArrayName { x := &longArrayName[i] //this also declares x to be a *struct{field1 int} x.field = value xrefs = append(xrefs, x) }