Last active
May 19, 2016 09:23
-
-
Save oyvindsk/8a41c34248e0eb81ca0c838c9d155b1c to your computer and use it in GitHub Desktop.
go vet on closed over loop
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# One might think this "should" be caught by go vet, but it's not in my simple test. | |
# | |
# From go doc cmd/vet: | |
## | |
## Range loop variables | |
## | |
## Flag: -rangeloops | |
## | |
## Incorrect uses of range loop variables in closures. | |
## | |
## | |
## Shadowed variables | |
## | |
## Flag: -shadow=false (experimental; must be set explicitly) | |
## | |
## Variables that may have been unintentionally shadowed. | |
os@os-900:/tmp$ go run foo.go | |
Example A - Count to 2, This works :) | |
a is: 0 | |
a is: 1 | |
a is: 2 | |
Example B - Count to 2, concurrently. | |
This does not work :( | |
b is: 3 | |
b is: 3 | |
b is: 3 | |
os@os-900:/tmp$ go vet foo.go | |
os@os-900:/tmp$ | |
os@os-900:/tmp$ go tool vet -shadow -shadowstrict foo.go | |
os@os-900:/tmp$ | |
# From http://oyvindsk.com/writing/common-golang-mistakes-1 | |
os@os-900:/tmp$ cat foo.go | |
package main | |
import ( | |
"fmt" | |
"time" | |
) | |
func main() { | |
// A | |
fmt.Println("Example A - Count to 2, This works :) ") | |
for a := 0; a < 3; a++ { | |
fmt.Println("a is:", a) | |
} | |
// B | |
fmt.Println("\n\nExample B - Count to 2, concurrently.") | |
fmt.Println("This does not work :( ") | |
for b := 0; b < 3; b++ { | |
// Run fmt.Println(..) in the background | |
go func() { | |
fmt.Println("b is:", b) | |
}() | |
} | |
// we sleep to let the go functions finish before the program quits | |
time.Sleep(2 * time.Second) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment