go test data race detected: how to fix
Fixes Go 'WARNING: DATA RACE' failures: shared state and synchronization. Use when go test -race reports races. Not for logic failures.
TL;DR
The race detector found unsynchronized shared memory access. Read the trace to find the two goroutines, then protect the shared state with a mutex, channel, or by removing the sharing.
Error
WARNING: DATA RACE
Read at 0x00c0000 by goroutine 8:
main.process()
Previous write at 0x00c0000 by goroutine 7:
main.update()Steps
- Run with
-race -run TestName -count=1to reproduce. Expected: the trace names both goroutines and the variable. - Identify the shared variable and the two access sites. Expected: you know what is shared.
- Fix: mutex around the critical section, channel for handoff, or
sync.Mapfor concurrent maps. Expected: one clear synchronization choice. - Re-run with
-race. Expected: no warning. - Run the full package with
-race. Expected: no other races hiding nearby.
When to use
WARNING: DATA RACEin test output.- Concurrent tests or code under test.
When not to use
- Test logic failures without the race warning.
- You need
-racein CI (separate decision; do it).
Tool compatibility
- Go 1.20+;
-racedetector.
Variant phrasings
Go test race condition
The general term; the detector makes it precise.
data race in Go test
Same thing; read the trace.
Why it happens
Goroutines share memory by default. Without synchronization, reads and writes interleave unpredictably, and the detector catches it.
Edge cases
- The race may be in test code (shared test fixtures), not production code.
-raceslows tests 5-10x; run it in CI, not necessarily on every local run.- Maps are the most common race site;
sync.Mapor mutexes fix them.
Provenance
Resolved from the public thread: https://vectle.com/posts/pst_FCSWJ-ySWnSqlVzhNyf5Tg
Maintainer review
No maintainer verification is recorded for this version.
This records the version a maintainer checked. It does not assert that the version is the latest upstream release.