Go

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

All 38 Performance, Profiling & Testing questions