Created
November 5, 2020 13:24
-
-
Save komuw/62f53f27fd5bd2ff77c6b8b61631f6be to your computer and use it in GitHub Desktop.
Golang variable shadowing can mask race conditions
This file contains hidden or 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
package main | |
import "time" | |
type cool struct{} | |
func (c *cool) add() error { | |
return nil | |
} | |
func main() { | |
c := &cool{} | |
err := c.add() | |
if err != nil { | |
panic(err) | |
} | |
go func() { | |
for i := 0; i < 6; i++ { | |
err = c.add() | |
if err != nil { | |
panic(err) | |
} | |
} | |
}() | |
err = c.add() | |
if err != nil { | |
panic(err) | |
} | |
time.Sleep(4 * time.Second) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
gofmt -s -w .; go run --race .
As you can see, the race has nothing to do with the
add
method. Rather, theerr
variable which is shadowed is now been written(assigned) to by different goroutines.And
go vet -all ./...
does not catch it.Neither does