go / expert
Snippet
Safe Concurrent Table-Driven Subtests via Closure Variable Re-binding
When combining table-driven tests with t.Parallel(), subtests run concurrently in separate goroutines. Capturing the loop iteration variable directly inside the closure leads to race conditions where subtests read mutated loop variables. Re-binding 'tt := tt' inside the loop scope ensures each subtest receives a distinct, isolated memory copy of its test case data.
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
25
26
27
package validator_testimport ("testing")func TestValidateInput(t *testing.T) {tests := []struct {name stringinput stringisValid bool}{{"empty string", "", false},{"no domain", "user@", false},}for _, tt := range tests {tt := ttt.Run(tt.name, func(t *testing.T) {t.Parallel()if result := (len(tt.input) > 3); result != tt.isValid {t.Errorf("got %v, want %v", result, tt.isValid)}})}}
Breakdown
1
tt := tt
Re-binds the loop iteration variable to a block-scoped variable to isolate it per goroutine.
2
t.Run(tt.name, func(t *testing.T) {
Spawns a named subtest closure that safely references the local copy of tt.
3
t.Parallel()
Signals to the Go test runner that this subtest can be executed concurrently alongside other parallel tests.