go / expert
Snippet
Parallel Table-Driven Subtest Isolation and Execution Synchronization
When executing table-driven subtests in parallel using t.Parallel(), subtest closures capture loop iteration variables by reference. Re-binding the range variable inside the loop scope ensures that concurrent subtests evaluate distinct test inputs rather than referencing the final iteration state.
snippet.go
go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package mainimport ("testing")func TestParallelSubtests(t *testing.T) {tests := []struct {name stringvalue int}{{"case_a", 10},{"case_b", 20},}for _, tt := range tests {tt := ttt.Run(tt.name, func(t *testing.T) {t.Parallel()if tt.value <= 0 {t.Errorf("expected positive value, got %d", tt.value)}})}}
Breakdown
1
for _, tt := range tests {
Iterates through the slice of test case structs.
2
tt := tt
Shadows the loop variable into a local block scope to prevent data races during parallel subtest execution.
3
t.Run(tt.name, func(t *testing.T) {
Launches a named subtest closure within the parent test context.
4
t.Parallel()
Marks the subtest to run concurrently alongside other parallel tests.