Race Detection
Start with Race Detection
In this lesson, explore race detection through one small Go program, and connect its output to the language rules behind it.
What you’ll learn
- Explain the main purpose of race detection.
- Read and run the complete Go example in this lesson.
- Apply the concept and recognize common mistakes.
Understand the idea
The Go race detector instruments memory accesses to find data races that happen during a test or run. Use go test -race ./... or go run -race main.go.
It reports races observed during execution; a clean run does not prove all possible paths are race-free.
Visualize how it works
Follow this diagram before executing the example. Check where a value or decision changes what runs next.
Tools, syntax and practical notes
Command-line check: go run -race main.go. Read the race detector guide.
Run a complete Go example
This example is a complete program. Save it as main.go or paste it into the Go Playground.
Go code
package main
import (
"fmt"
"sync"
)
func main() {
var wg sync.WaitGroup
numbers := make([]int, 3)
for i := range numbers {
wg.Add(1)
go func(index int) { defer wg.Done(); numbers[index] = index + 1 }(i)
}
wg.Wait()
fmt.Println(numbers)
}
Output
[1 2 3]Trace what the program does
Each worker writes a different slice element and Wait establishes completion before the printed read. It is suitable to run with -race as a passing example.
Avoid common mistakes
- -race adds overhead and does not replace code review.
- Two goroutines writing different indexes of a pre-sized slice is different from concurrently appending to its header.
Try it yourself
Run this with go run -race main.go; then experiment with an intentionally shared counter in a disposable scratch program.
Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.
Check your understanding
What you should remember
You have practiced Race Detection in a small, self-contained program. The important habit is to predict what runs, inspect the actual output and distinguish the language rule from the particular example.
Before continuing, make sure you can explain the program to someone who has not seen it, including the line that changes its result.
Reaching the recap and completing the quizzes are separate milestones.