Race detector
The race detector is a compiler and runtime instrument you enable with go test -race or go build -race. It reports concurrent unsynchronized access to the same memory when at least one access is a write.
Detailed Explanation
A data race is undefined behaviour in the memory model. The detector watches every memory access in the instrumented build and compares them to the happens-before edges created by channels, mutexes, atomic, and WaitGroup. If two goroutines touch the same word without a synchronizing edge, and one writes, it prints a stack for both and exits the test (or logs, depending on GORACE).
How you run it. go test -race ./... in CI is the baseline. go run -race and go build -race exist for reproducing a live race. The instrumented binary is slower (often 2–10×) and uses more memory. Do not ship -race binaries as production defaults; use them in tests and when hunting a race.
What it cannot see. Races that do not happen on that run are not reported. A test that never starts two goroutines will not find a race in a helper those tests never call. Coverage of concurrent paths matters. The detector also does not prove lock-freedom or deadlock-freedom.
False sense of security. A green -race run means "no race on this execution," not "the package is race-free." Still write the lock or the channel protocol so the next call site cannot invent a race.
What it costs. Compile time and runtime overhead. In CI, run -race on unit tests; maybe not on every integration test if the suite is huge — but the unit tests that start goroutines are the ones you must not skip.
Code Examples
package count
import "testing"
func TestIncRace(t *testing.T) {
var n int
done := make(chan struct{}, 2)
inc := func() {
n++
done <- struct{}{}
}
go inc()
go inc()
<-done
<-done
t.Log(n)
}# From the module root. Reports the race in TestIncRace.
go test -race ./...# Optional: keep going after the first report.
GORACE=halt_on_error=0 go test -race ./...Common Gotchas
A race-free test run is not a proof
add tests that actually overlap the critical sections.
`-race` binaries are slow and large
keep them off the default production build.
`sync/atomic` and channels create happens-before
the detector treats them as synchronization, same as mutexes.
Cgo and some syscalls are not fully instrumented
a race through C memory may be missed.