June 26, 2020

Golang range gotcha

In golang, when you range through an array of elements as in the following:

// THIS CODE IS WRONG; DO NOT USE THIS
for i,v := range elements {
    go do_something(v)
}

In the above example, the value of v may change while do_something tries to used it. This is a race condition and will definitely cause problem. To fix this, one should use elements[i] instead;

No comments:

Post a Comment