Somethings one can observe strange v := v
in Go source code. And there is a reason behind it. Take this code from Go FAQ for example:
|
|
Output of this code is predictable and contains all the values from values
variable.:
c
b
a
But if we remove line 5, logic is broken:
c
c
c
This is simple case to remember, sure. Just use one of ‘workarounds’: assign value to inner variable (v := v
), or use is an argument for the go routine ( go func(u ...) {...}(v)
).
But there are more subtle ways to shoot yourself. By tests for example. Unfortenately tests are code as well, and can be false positive (snippet from Go Wiki):
|
|
And this test will pass :(. Sometimes odd numbers are even. And here only v := v
appears to be applicable, as we can’t easily redefine t.Run()
for pass extra arguments.
References:
- go.dev: FAQ - What happens with closures running as goroutines?
- github: golang wiki LoopvarExperiment
- github: golang issue 56010
- github: golang issue 60078
Thu Jul 13, 2023 / 285 words / Golang Programming Gotchas