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

Go Documentation Generation and Example Code

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 Type Function Name
Package Example Example()
Function Example ExampleFuncName()
Type Example ExampleTypeName()
Method Example ExampleTypeName_MethodName()
Multiple Examples ExampleTypeName_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

Tool Purpose
stringer Generates String() method for enum types
mockgen Generates mock implementations for interfaces
protoc Generates Go code from .proto files
sqlc Generates type-safe Go code from SQL
enumer Enum generation (more powerful than stringer)
go-bindata Embeds 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

Feature Description
Comments as Documentation Comments placed directly above declarations automatically become documentation
Example Tests Both executable documentation and test cases
go doc View documentation from the command line
godoc -http Local Web documentation service
pkg.go.dev Online documentation for public packages
go generate Code generation before compilation
//go:embed Embed static assets into binaries (Go 1.16+)

主题测试文章,只做测试使用。发布者:Walker,转转请注明出处:https://walker-learn.xyz/archives/6749

(0)
Walker的头像Walker
上一篇 13 hours ago
下一篇 1 day ago

Related Posts

EN
简体中文 繁體中文 English