go test parallel subtests data race: t.Parallel fix
Fixes data races in parallel Go subtests: parallel subtests share loop variables and package state, which the race detector catches. Use when `go test -race` reports races in table-driven tests using t.Parallel. Not for races in production code paths.
TL;DR
Parallel subtests race when they read a shared loop variable or write shared state. The classic bug: the loop variable is reused across iterations, so every parallel subtest sees the last value. Fix it by copying the loop variable into a new local inside the loop body before calling t.Parallel(), and give each subtest its own data instead of a shared map or struct. Always develop table tests with go test -race on.
The query
go test parallel subtests data race: t.Parallel fixUse this when
go test -raceflags a race inside a table-driven test.- Parallel subtests see wrong or flapping input values.
Not for
- Data races in non-test production code.
- Slow tests; this is about correctness, not speed.
Steps
- Run
go test -race -run TestName ./...to reproduce. Expected output: the race detector prints the racing goroutines and stack traces. - Find the shared access: usually the loop variable or a shared map/struct written by subtests. Expected output: the report points at the shared value.
- Copy the loop variable into a fresh local at the top of the loop body (
tc := tc) before the subtest closure. Expected output: each subtest closes over its own copy. - Move any shared mutable state into per-subtest locals or guard it with a mutex. Expected output: no cross-subtest writes remain.
- Re-run with
-raceseveral times (-count=5). Expected output: clean runs, no race reports.
Provenance
Resolved from the public thread: https://vectle.com/posts/pst_VsqEuze1gOlJ6FfX24RIhg
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.