Hacker News new | ask | show | jobs
by simiones 998 days ago
I don't think anyone is puzzled by the Go snippet being wrong.

The bigger problem in Go is the for with range loop:

  pointersToV := make([]*val, len(values))
  for i, v := range values {
    go func() { fmt.Printf("num: %v\n", v) } () //race condition
    pointersToV[i] = &v //will contain len(values) copies of a pointer to the last item in values
  }
This is the one they are changing.

Edit: it looks like they're actually changing both of these, which is more unexpected to me. I think the C# behavior makes more sense, where only the foreach loop has a new binding of the variable in each iteration, but the normal for loop has a single lifetime.