Managing data races
When multiple goroutines access shared data or resources concurrently, a “race condition” can occur. As we can attest, this type of concurrency bug can lead to unpredictable and undesirable behavior. The Go test tool has a built-in feature called Go race detection that can detect and identify race conditions in your Go code.
So, let’s create a main_test.go
file with a simple test case:
package main import ( "testing" ) func TestPackItems(t *testing.T) { totalItems := PackItems(2000) expectedTotal := 2000 if totalItems != expectedTotal { t.Errorf("Expected total: %d, Actual total: %d", expectedTotal, totalItems) } }
Now, let’s use the race detector:
go test -race
The result in the console will be...