Documentation and APIs
Overview
Good documentation makes code usable. Go has built-in tools for extracting docs from source comments.
Writing Doc Comments
// Package math provides mathematical utilities.
//
// It includes functions for basic arithmetic and
// statistical calculations.
package math
// Pi represents the mathematical constant π.
const Pi = 3.14159
// Add returns the sum of a and b.
func Add(a, b int) int {
return a + b
}
// Calculator provides stateful calculations.
type Calculator struct {
// Result holds the current value.
Result float64
}Conventions
- Start with the name being documented
- Use complete sentences
- First sentence is the summary
Examples
func ExampleAdd() {
result := Add(2, 3)
fmt.Println(result)
// Output: 5
}Viewing Docs
go doc fmt
go doc fmt.Println
go doc -all mypackagepkg.go.dev
Public packages are automatically documented at:
https://pkg.go.dev/github.com/user/package
API Design Guidelines
// Accept interfaces, return structs
func Process(r io.Reader) (*Result, error)
// Use functional options
func NewServer(opts ...Option) *Server
// Clear error messages
return fmt.Errorf("user %d: %w", id, err)Summary
| Tool | Purpose |
|---|---|
go doc |
View documentation |
godoc |
Local doc server |
| pkg.go.dev | Public package docs |
| Examples | Testable documentation |