Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

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?


Yes, 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)
  }




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: