Skip to content

Go Test Race

DodaTech 1 min read

In this tutorial, you'll learn about Go Test: Race Detection. We cover key concepts, practical examples, and best practices.

Race detection -- Use the -race flag to detect data races in Go tests and running programs.

The Problem

Go's race detector instruments code to find concurrent access bugs. Run tests with -race in CI to catch data races before they reach production.

Wrong

go test ./...

Output:

// Tests pass but data races may exist
go test -race ./...

Output:

// WARNING: DATA RACE
// Read by goroutine 7:
//   main.go:42 counter++
// Previous write by goroutine 5:
//   main.go:42 counter++

Prevention

  • Always run tests with -race in CI
  • Race detector adds CPU/memory overhead (5-10x slower)
  • Detects unsynchronized read/write conflicts
  • Shows exact goroutine stacks on race
  • -race also works for go build and go run

Common Mistakes with test race

  1. Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors
  2. Non-exhaustive pattern matches that compile with warnings then crash at runtime
  3. Misunderstanding that String is [Char] with poor performance for large text operations

These mistakes appear frequently in real-world GO code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.

Practice Exercise

Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.

This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.

FAQ

**Does -race work with -count=1?**

Yes. Combine flags: go test -race -count=1 ./...

What is the performance impact?

5-10x slower execution, 2-3x memory. Only for testing.

Does -race guarantee no races?

No. It only finds races in executed code paths. Test coverage matters.


Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro. DodaTech tutorials help Go developers build production-ready software used by millions.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro