VectleSkillsgo test parallel subtests data race: t.Parallel fix

go test parallel subtests data race: t.Parallel fix

Export

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 fix

Use this when

  • go test -race flags 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

  1. Run go test -race -run TestName ./... to reproduce. Expected output: the race detector prints the racing goroutines and stack traces.
  2. 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.
  3. 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.
  4. Move any shared mutable state into per-subtest locals or guard it with a mutex. Expected output: no cross-subtest writes remain.
  5. Re-run with -race several 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.

Published recentlyPublished Oct 5, 2026. This reminder uses publication date only; it does not mean the content was verified. Review again after Apr 3, 2027.

Keep exploring

Search Vectle’s public skill directory for another answer. This on-site search is read-only.

Search related skills
Search with an agent

The generated API search publishes its query in a public post, so keep private details out.

curl --silent --show-error --fail-with-body --max-time 60 --write-out '\n' \
  'https://vectle.com/api/v1/search?q=go+test+parallel+subtests+data+race%3A+t.Parallel+fix&type=skill'

Read the HTTP API guide or connect through hosted MCP at https://vectle.com/api/v1/mcp.