What are Example functions, and how are they verified?
Question 401MediumGo 1.22 to 1.25
Functions named ExampleXxx in _test.go files serve as both documentation (rendered on pkg.go.dev next to the identifier) and tests. If the function ends with an // Output: comment, go test runs it and compares stdout exactly (trimming leading/trailing whitespace). // Unordered output: compares lines in any order — useful when iterating maps. Without an output comment, the example is compiled but not run.
package stack_test
import (
"fmt"
"example.com/stack"
)
func ExampleStack_Pop() {
var s stack.Stack[int]
s.Push(1)
s.Push(2)
v, ok := s.Pop()
fmt.Println(v, ok)
// Output: 2 true
}
func ExampleKeys() {
for k := range stack.Keys(map[string]int{"a": 1, "b": 2}) {
fmt.Println(k)
}
// Unordered output:
// a
// b
}
Naming: Example (package), ExampleF (function), ExampleT (type), ExampleT_M (method), with an optional _suffix for multiple variants. Using the external _test package forces you to use only the exported API, which is exactly what readers see. Interviewer is looking for: documentation that can't go stale because CI verifies it.
More on Performance, Profiling & Testing
- Q399How does the race detector work, what does it cost, and what are its limits?
- Q400How do you separate unit tests from slow integration tests, and what are golden files?
- Q402Walk through how you would investigate a service whose p99 latency doubled after a deploy.
- Q403How do you write a test that fails if a hot path starts allocating? Explain testing.AllocsPerRun and its caveats.
- Q404How do you benchmark concurrent code with b.RunParallel, and why does sync.RWMutex often fail to scale for read-heavy workloads?
- Q405Go 1.24 replaced the built-in map implementation with Swiss tables. What changed, and what does it mean for performance-sensitive code?