Skip to main content
Go: Documentation and Testable Examples
  1. Posts/

Go: Documentation and Testable Examples

Roman
Author
Roman
Photographer with MSci in Computer Science and a Home Lab obsession
Table of Contents

Following the Learn Go with Tests guide.

Function Documentation
#

Go uses comments above functions to create documentation that integrates with the standard toolchain:

// Add takes two integers and returns the sum of them.
func Add(x, y int) int {
	return x + y
}

Documentation Comments: Appear in go doc output and documentation websites like pkg.go.dev.

Testable Examples
#

Go supports executable examples that compile and run with your tests:

func ExampleAdd() {
	sum := Add(1, 5)
	fmt.Println(sum)
	// Output: 6
}

Example Function Features
#

  • Prefix: Begin with Example (like tests begin with Test)
  • Location: Live in _test.go files
  • Compilation: Compiled and executed with tests
  • Output verification: Special // Output: comment makes them executable, without they are compiled but not executed
  • Documentation: Appear in generated documentation

Running Examples
#

go test -v
# === RUN   TestAdder
# --- PASS: TestAdder (0.00s)
# === RUN   ExampleAdd  
# --- PASS: ExampleAdd (0.00s)

Viewing Documentation
#

# Install pkgsite if not already installed
go install golang.org/x/pkgsite/cmd/pkgsite@latest

# View local documentation
pkgsite -open .