← Back
后端开发 2026.03.06

Go Senior Engineer Lecture (MOOC) 007_godoc and Code Generation

后端开发

Corresponds to Video 8-6: Generating Documentation and Example Code

1. godoc Documentation Generation

Go’s documentation is extracted directly from source code comments, without requiring special markup syntax.

1.1 Comment Conventions

// Package queue implements a simple FIFO queue.
//
// The queue is slice-based and supports Push, Pop, and IsEmpty operations.
package queue

// Queue represents an integer first-in, first-out queue.
type Queue []int

// Push adds element v to the end of the queue.
func (q *Queue) Push(v int) {
    *q = append(*q, v)
}

// Pop removes and returns the element at the front of the queue.
// Panics if the queue is empty.
func (q *Queue) Pop() int {
    head := (*q)[0]
    *q = (*q)[1:]
    return head
}

// IsEmpty returns whether the queue is empty.
func (q *Queue) IsEmpty() bool {
    return len(*q) == 0
}

Rules: - Comments are placed directly above the declaration, starting with the name of the commented object. - Package comments are written above the package statement (or in a separate doc.go file). - Blank lines separate paragraphs. - Indented text will be displayed as a code block.

1.2 Viewing Documentation

# Start godoc service locally (built-in before Go 1.12, requires installation after)
go install golang.org/x/tools/cmd/godoc@latest
godoc -http :6060
# Access http://localhost:6060 in your browser

# View from command line
go doc fmt
go doc fmt.Println
go doc -all queue       # View all documentation for the package

1.3 pkg.go.dev

Packages published to GitHub automatically generate documentation on pkg.go.dev, requiring no additional action.

2. Example Tests (Executable Documentation)

Example functions serve as both documentation and tests, and are written in _test.go files:

// queue_test.go
package queue_test

import (
    "fmt"
    "myproject/queue"
)

// Package-level example
func Example() {
    q := queue.Queue{1}
    q.Push(2)
    q.Push(3)
    fmt.Println(q.Pop())
    fmt.Println(q.Pop())
    fmt.Println(q.IsEmpty())
    // Output:
    // 1
    // 2
    // false
}

// Method-level example
func ExampleQueue_Push() {
    var q queue.Queue
    q.Push(1)
    q.Push(2)
    fmt.Println(q)
    // Output:
    // [1 2]
}

func ExampleQueue_IsEmpty() {
    var q queue.Queue
    fmt.Println(q.IsEmpty())
    q.Push(1)
    fmt.Println(q.IsEmpty())
    // Output:
    // true
    // false
}

Naming Rules

Example TypeFunction Name
Package ExampleExample()
Function ExampleExampleFuncName()
Type ExampleExampleTypeName()
Method ExampleExampleTypeName_MethodName()
Multiple ExamplesExampleTypeName_MethodName_suffix()

Output Comments

  • // Output: — Exact match for output
  • // Unordered output: — Order of output does not matter (suitable for map iteration, etc.)
  • No Output comment → Only compiles, does not run (only checks for successful compilation)
# Run example tests
go test -v -run Example

When godoc is run, Example functions are automatically displayed on the documentation page for the corresponding function/type, and include a Run button.

3. go generate

go generate is used to run code generation tools before compilation.

3.1 Basic Usage

Add special comments in Go source files:

//go:generate stringer -type=Pill
package painkiller

type Pill int

const (
    Placebo Pill = iota
    Aspirin
    Ibuprofen
    Paracetamol
)
# Install stringer tool
go install golang.org/x/tools/cmd/stringer@latest

# Run generate (executes all //go:generate directives in the file)
go generate ./...

This automatically generates pill_string.go, containing the String() method for the Pill type.

3.2 Common `go generate` Uses

ToolPurpose
stringerGenerates String() method for enum types
mockgenGenerates mock implementations for interfaces
protocGenerates Go code from .proto files
sqlcGenerates type-safe Go code from SQL
enumerEnum generation (more powerful than stringer)
go-bindataEmbeds static assets into binaries

3.3 Go 1.16+ embed (Replaces go-bindata)

package main

import (
    "embed"
    "fmt"
    "net/http"
)

//go:embed static/*
var staticFiles embed.FS

//go:embed config.json
var config []byte

//go:embed version.txt
var version string

func main() {
    fmt.Println("Version:", version)
    fmt.Println("Config:", string(config))

    // Static file service
    http.Handle("/static/",
        http.FileServer(http.FS(staticFiles)))
    http.ListenAndServe(":8080", nil)
}

4. Summary

FeatureDescription
Comments as DocumentationComments placed directly above declarations automatically become documentation
Example TestsBoth executable documentation and test cases
go docView documentation from the command line
godoc -httpLocal Web documentation service
pkg.go.devOnline documentation for public packages
go generateCode generation before compilation
//go:embedEmbed static assets into binaries (Go 1.16+)