go-documentation

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Go Documentation

Go语言文档编写指南

This skill covers documentation conventions from Google's Go Style Guide.

本指南涵盖了Google Go语言风格指南中的文档编写规范。

Doc Comments

文档注释

Normative: All top-level exported names must have doc comments.
规范性要求:所有顶层导出的名称必须包含文档注释。

Basic Rules

基本规则

  1. Begin with the name of the object being described
  2. An article ("a", "an", "the") may precede the name
  3. Use full sentences (capitalized, punctuated)
go
// Good:
// A Request represents a request to run a command.
type Request struct { ...

// Encode writes the JSON encoding of req to w.
func Encode(w io.Writer, req *Request) { ...
  1. 以所描述对象的名称开头
  2. 名称前可加冠词("a"、"an"、"the")
  3. 使用完整句子(首字母大写,结尾加标点)
go
// Good:
// A Request represents a request to run a command.
type Request struct { ...

// Encode writes the JSON encoding of req to w.
func Encode(w io.Writer, req *Request) { ...

Struct Documentation

结构体文档

go
// Good:
// Options configure the group management service.
type Options struct {
    // General setup:
    Name  string
    Group *FooGroup

    // Dependencies:
    DB *sql.DB

    // Customization:
    LargeGroupThreshold int // optional; default: 10
    MinimumMembers      int // optional; default: 2
}
Unexported types/functions with unobvious behavior should also have doc comments. Use the same style to make future exporting easy.

go
// Good:
// Options configure the group management service.
type Options struct {
    // General setup:
    Name  string
    Group *FooGroup

    // Dependencies:
    DB *sql.DB

    // Customization:
    LargeGroupThreshold int // optional; default: 10
    MinimumMembers      int // optional; default: 2
}
对于行为不明显的未导出类型/函数,也应添加文档注释。使用相同的风格编写,以便未来导出时无需修改格式。

Comment Sentences

注释句子

Normative: Documentation comments must be complete sentences.
  • Capitalize the first word, end with punctuation
  • Exception: may begin with uncapitalized identifier if clear
  • End-of-line comments for struct fields can be phrases:
go
// Good:
// A Server handles serving quotes from Shakespeare.
type Server struct {
    // BaseDir points to the base directory for Shakespeare's works.
    //
    // Expected structure:
    //   {BaseDir}/manifest.json
    //   {BaseDir}/{name}/{name}-part{number}.txt
    BaseDir string

    WelcomeMessage  string // displayed when user logs in
    ProtocolVersion string // checked against incoming requests
    PageLength      int    // lines per page (optional; default: 20)
}

规范性要求:文档注释必须是完整的句子。
  • 首字母大写,结尾加标点
  • 例外情况:若含义清晰,可以小写标识符开头
  • 结构体字段的行尾注释可以使用短语:
go
// Good:
// A Server handles serving quotes from Shakespeare.
type Server struct {
    // BaseDir points to the base directory for Shakespeare's works.
    //
    // Expected structure:
    //   {BaseDir}/manifest.json
    //   {BaseDir}/{name}/{name}-part{number}.txt
    BaseDir string

    WelcomeMessage  string // displayed when user logs in
    ProtocolVersion string // checked against incoming requests
    PageLength      int    // lines per page (optional; default: 20)
}

Comment Line Length

注释行长度

Advisory: Aim for ~80 columns, but no hard limit.
text
undefined
建议性要求:目标长度约80列,但无硬性限制。
text
undefined

Good:

Good:

// This is a comment paragraph. // The length of individual lines doesn't matter in Godoc; // but the choice of wrapping makes it easy to read on narrow screens. // // Don't worry too much about the long URL: // https://supercalifragilisticexpialidocious.example.com:8080/Animalia/Chordata/
// This is a comment paragraph. // The length of individual lines doesn't matter in Godoc; // but the choice of wrapping makes it easy to read on narrow screens. // // Don't worry too much about the long URL: // https://supercalifragilisticexpialidocious.example.com:8080/Animalia/Chordata/

Bad:

Bad:

// This is a comment paragraph. The length of individual lines doesn't matter in Godoc; // but the choice of wrapping causes jagged lines on narrow screens or in code review.

Break based on punctuation. Don't split long URLs.

---
// This is a comment paragraph. The length of individual lines doesn't matter in Godoc; // but the choice of wrapping causes jagged lines on narrow screens or in code review.

根据标点换行,不要拆分长URL。

---

Package Comments

包注释

Normative: Every package must have exactly one package comment.
go
// Good:
// Package math provides basic constants and mathematical functions.
//
// This package does not guarantee bit-identical results across architectures.
package math
规范性要求:每个包必须且只能有一个包注释。
go
// Good:
// Package math provides basic constants and mathematical functions.
//
// This package does not guarantee bit-identical results across architectures.
package math

Main Packages

主包

Use the binary name (matching the BUILD file):
go
// Good:
// The seed_generator command is a utility that generates a Finch seed file
// from a set of JSON study configs.
package main
Valid styles:
Binary seed_generator
,
Command seed_generator
,
The seed_generator command
,
Seed_generator ...
Tips:
  • For long package comments, use a
    doc.go
    file
  • Maintainer comments after imports don't appear in Godoc

使用二进制名称(与BUILD文件匹配):
go
// Good:
// The seed_generator command is a utility that generates a Finch seed file
// from a set of JSON study configs.
package main
有效风格:
Binary seed_generator
Command seed_generator
The seed_generator command
Seed_generator ...
提示:
  • 对于较长的包注释,使用
    doc.go
    文件
  • 导入语句后的维护者注释不会在Godoc中显示

Parameters and Configuration

参数与配置

Advisory: Document error-prone or non-obvious parameters, not everything.
go
// Bad: Restates the obvious
// Sprintf formats according to a format specifier and returns the resulting string.
//
// format is the format, and data is the interpolation data.
func Sprintf(format string, data ...any) string

// Good: Documents non-obvious behavior
// Sprintf formats according to a format specifier and returns the resulting string.
//
// The provided data is used to interpolate the format string. If the data does
// not match the expected format verbs or the amount of data does not satisfy
// the format specification, the function will inline warnings about formatting
// errors into the output string.
func Sprintf(format string, data ...any) string

建议性要求:仅文档化易出错或不明显的参数,无需全部说明。
go
// Bad: Restates the obvious
// Sprintf formats according to a format specifier and returns the resulting string.
//
// format is the format, and data is the interpolation data.
func Sprintf(format string, data ...any) string

// Good: Documents non-obvious behavior
// Sprintf formats according to a format specifier and returns the resulting string.
//
// The provided data is used to interpolate the format string. If the data does
// not match the expected format verbs or the amount of data does not satisfy
// the format specification, the function will inline warnings about formatting
// errors into the output string.
func Sprintf(format string, data ...any) string

Contexts

Context上下文

Advisory: Don't restate implied context behavior; document exceptions.
Context cancellation is implied to interrupt the function and return
ctx.Err()
. Don't document this.
go
// Bad: Restates implied behavior
// Run executes the worker's run loop.
//
// The method will process work until the context is cancelled.
func (Worker) Run(ctx context.Context) error

// Good: Just the essential
// Run executes the worker's run loop.
func (Worker) Run(ctx context.Context) error
Document when behavior differs:
go
// Good: Non-standard cancellation behavior
// Run executes the worker's run loop.
//
// If the context is cancelled, Run returns a nil error.
func (Worker) Run(ctx context.Context) error

// Good: Special context requirements
// NewReceiver starts receiving messages sent to the specified queue.
// The context should not have a deadline.
func NewReceiver(ctx context.Context) *Receiver

建议性要求:不要重复说明隐含的上下文行为;仅文档化例外情况。
Context取消会中断函数并返回
ctx.Err()
是隐含行为,无需文档化。
go
// Bad: Restates implied behavior
// Run executes the worker's run loop.
//
// The method will process work until the context is cancelled.
func (Worker) Run(ctx context.Context) error

// Good: Just the essential
// Run executes the worker's run loop.
func (Worker) Run(ctx context.Context) error
当行为不同时需要文档化:
go
// Good: Non-standard cancellation behavior
// Run executes the worker's run loop.
//
// If the context is cancelled, Run returns a nil error.
func (Worker) Run(ctx context.Context) error

// Good: Special context requirements
// NewReceiver starts receiving messages sent to the specified queue.
// The context should not have a deadline.
func NewReceiver(ctx context.Context) *Receiver

Concurrency

并发

Advisory: Document non-obvious thread safety characteristics.
Read-only operations are assumed safe; mutating operations are assumed unsafe. Don't restate this.
Document when:
go
// Ambiguous operation (looks read-only but mutates internally)
// Lookup returns the data associated with the key from the cache.
//
// This operation is not safe for concurrent use.
func (*Cache) Lookup(key string) (data []byte, ok bool)

// API provides synchronization
// NewFortuneTellerClient returns an *rpc.Client for the FortuneTeller service.
// It is safe for simultaneous use by multiple goroutines.
func NewFortuneTellerClient(cc *rpc.ClientConn) *FortuneTellerClient

// Interface has concurrency requirements
// A Watcher reports the health of some entity (usually a backend service).
//
// Watcher methods are safe for simultaneous use by multiple goroutines.
type Watcher interface {
    Watch(changed chan<- bool) (unwatch func())
    Health() error
}

建议性要求:文档化不明显的线程安全特性。
只读操作默认是安全的;修改操作默认是不安全的,无需重复说明。
以下情况需要文档化:
go
// Ambiguous operation (looks read-only but mutates internally)
// Lookup returns the data associated with the key from the cache.
//
// This operation is not safe for concurrent use.
func (*Cache) Lookup(key string) (data []byte, ok bool)

// API provides synchronization
// NewFortuneTellerClient returns an *rpc.Client for the FortuneTeller service.
// It is safe for simultaneous use by multiple goroutines.
func NewFortuneTellerClient(cc *rpc.ClientConn) *FortuneTellerClient

// Interface has concurrency requirements
// A Watcher reports the health of some entity (usually a backend service).
//
// Watcher methods are safe for simultaneous use by multiple goroutines.
type Watcher interface {
    Watch(changed chan<- bool) (unwatch func())
    Health() error
}

Cleanup

资源清理

Advisory: Always document explicit cleanup requirements.
go
// Good:
// NewTicker returns a new Ticker containing a channel that will send the
// current time on the channel after each tick.
//
// Call Stop to release the Ticker's associated resources when done.
func NewTicker(d Duration) *Ticker

// Good: Show how to clean up
// Get issues a GET to the specified URL.
//
// When err is nil, resp always contains a non-nil resp.Body.
// Caller should close resp.Body when done reading from it.
//
//    resp, err := http.Get("http://example.com/")
//    if err != nil {
//        // handle error
//    }
//    defer resp.Body.Close()
//    body, err := io.ReadAll(resp.Body)
func (c *Client) Get(url string) (resp *Response, err error)

建议性要求:必须文档化明确的资源清理要求。
go
// Good:
// NewTicker returns a new Ticker containing a channel that will send the
// current time on the channel after each tick.
//
// Call Stop to release the Ticker's associated resources when done.
func NewTicker(d Duration) *Ticker

// Good: Show how to clean up
// Get issues a GET to the specified URL.
//
// When err is nil, resp always contains a non-nil resp.Body.
// Caller should close resp.Body when done reading from it.
//
//    resp, err := http.Get("http://example.com/")
//    if err != nil {
//        // handle error
//    }
//    defer resp.Body.Close()
//    body, err := io.ReadAll(resp.Body)
func (c *Client) Get(url string) (resp *Response, err error)

Errors

错误处理

Advisory: Document significant error sentinel values and types.
go
// Good: Document sentinel values
// Read reads up to len(b) bytes from the File and stores them in b.
//
// At end of file, Read returns 0, io.EOF.
func (*File) Read(b []byte) (n int, err error)

// Good: Document error types (include pointer receiver)
// Chdir changes the current working directory to the named directory.
//
// If there is an error, it will be of type *PathError.
func Chdir(dir string) error
Noting
*PathError
(not
PathError
) enables correct use of
errors.Is
and
errors.As
.
For package-wide error conventions, document in the package comment.

建议性要求:文档化重要的错误哨兵值和错误类型。
go
// Good: Document sentinel values
// Read reads up to len(b) bytes from the File and stores them in b.
//
// At end of file, Read returns 0, io.EOF.
func (*File) Read(b []byte) (n int, err error)

// Good: Document error types (include pointer receiver)
// Chdir changes the current working directory to the named directory.
//
// If there is an error, it will be of type *PathError.
func Chdir(dir string) error
标注
*PathError
而非
PathError
,可以让开发者正确使用
errors.Is
errors.As
对于包级别的错误约定,在包注释中说明。

Examples

示例代码

Advisory: Provide runnable examples to demonstrate package usage.
Place examples in test files (
*_test.go
):
go
// Good:
func ExampleConfig_WriteTo() {
    cfg := &Config{
        Name: "example",
    }
    if err := cfg.WriteTo(os.Stdout); err != nil {
        log.Exitf("Failed to write config: %s", err)
    }
    // Output:
    // {
    //   "name": "example"
    // }
}
Examples appear in Godoc attached to the documented element.

建议性要求:提供可运行的示例代码,演示包的使用方法。
将示例代码放在测试文件(
*_test.go
)中:
go
// Good:
func ExampleConfig_WriteTo() {
    cfg := &Config{
        Name: "example",
    }
    if err := cfg.WriteTo(os.Stdout); err != nil {
        log.Exitf("Failed to write config: %s", err)
    }
    // Output:
    // {
    //   "name": "example"
    // }
}
示例代码会在Godoc中关联到对应的文档元素。

Godoc Formatting

Godoc格式规范

Advisory: Use godoc syntax for well-formatted documentation.
Paragraphs - Separate with blank lines:
go
// Good:
// LoadConfig reads a configuration out of the named file.
//
// See some/shortlink for config file format details.
Verbatim/Code blocks - Indent by two additional spaces:
go
// Good:
// Update runs the function in an atomic transaction.
//
// This is typically used with an anonymous TransactionFunc:
//
//   if err := db.Update(func(state *State) { state.Foo = bar }); err != nil {
//     //...
//   }
Lists and tables - Use verbatim formatting:
go
// Good:
// LoadConfig treats the following keys in special ways:
//   "import" will make this configuration inherit from the named file.
//   "env" if present will be populated with the system environment.
Headings - Single line, capital letter, no punctuation (except parens/commas), followed by paragraph:
go
// Good:
// Using headings
//
// Headings come with autogenerated anchor tags for easy linking.

建议性要求:使用godoc语法,生成格式规范的文档。
段落 - 使用空行分隔:
go
// Good:
// LoadConfig reads a configuration out of the named file.
//
// See some/shortlink for config file format details.
文本/代码块 - 额外缩进两个空格:
go
// Good:
// Update runs the function in an atomic transaction.
//
// This is typically used with an anonymous TransactionFunc:
//
//   if err := db.Update(func(state *State) { state.Foo = bar }); err != nil {
//     //...
//   }
列表与表格 - 使用原始格式:
go
// Good:
// LoadConfig treats the following keys in special ways:
//   "import" will make this configuration inherit from the named file.
//   "env" if present will be populated with the system environment.
标题 - 单行,首字母大写,无标点(括号/逗号除外),后面跟段落:
go
// Good:
// Using headings
//
// Headings come with autogenerated anchor tags for easy linking.

Named Result Parameters

命名返回参数

Advisory: Use for documentation when types alone aren't clear enough.
go
// Good: Multiple params of same type
func (n *Node) Children() (left, right *Node, err error)

// Good: Action-oriented name clarifies usage
// The caller must arrange for the returned cancel function to be called.
func WithTimeout(parent Context, d time.Duration) (ctx Context, cancel func())

// Bad: Type already clear, name adds nothing
func (n *Node) Parent1() (node *Node)
func (n *Node) Parent2() (node *Node, err error)

// Good: Type is sufficient
func (n *Node) Parent1() *Node
func (n *Node) Parent2() (*Node, error)
Don't name results just to enable naked returns. Clarity > brevity.

建议性要求:当仅通过类型无法清晰表达时,使用命名返回参数来辅助文档说明。
go
// Good: Multiple params of same type
func (n *Node) Children() (left, right *Node, err error)

// Good: Action-oriented name clarifies usage
// The caller must arrange for the returned cancel function to be called.
func WithTimeout(parent Context, d time.Duration) (ctx Context, cancel func())

// Bad: Type already clear, name adds nothing
func (n *Node) Parent1() (node *Node)
func (n *Node) Parent2() (node *Node, err error)

// Good: Type is sufficient
func (n *Node) Parent1() *Node
func (n *Node) Parent2() (*Node, error)
不要为了使用裸返回而命名结果参数。清晰性优先于简洁性。

Signal Boosting

重点标注

Advisory: Add comments to highlight unusual or easily-missed patterns.
These two are hard to distinguish:
go
if err := doSomething(); err != nil {  // common
    // ...
}

if err := doSomething(); err == nil {  // unusual!
    // ...
}
Add a comment to boost the signal:
go
// Good:
if err := doSomething(); err == nil { // if NO error
    // ...
}

建议性要求:添加注释来突出不常见或容易被忽略的代码模式。
以下两种写法难以区分:
go
if err := doSomething(); err != nil {  // common
    // ...
}

if err := doSomething(); err == nil {  // unusual!
    // ...
}
添加注释来突出重点:
go
// Good:
if err := doSomething(); err == nil { // if NO error
    // ...
}

Documentation Preview

文档预览

Advisory: Preview documentation before and during code review.
bash
go install golang.org/x/pkgsite/cmd/pkgsite@latest
pkgsite
This validates godoc formatting renders correctly.

建议性要求:在代码评审前和评审期间预览文档效果。
bash
go install golang.org/x/pkgsite/cmd/pkgsite@latest
pkgsite
此工具可验证godoc格式是否正确渲染。

Quick Reference

快速参考

TopicKey Rule
Doc commentsStart with name, use full sentences
Line length~80 chars, prioritize readability
Package commentsOne per package, above
package
clause
ParametersDocument non-obvious behavior only
ContextsDocument exceptions to implied behavior
ConcurrencyDocument ambiguous thread safety
CleanupAlways document resource release
ErrorsDocument sentinels and types (note pointer)
ExamplesUse runnable examples in test files
FormattingBlank lines for paragraphs, indent for code

主题核心规则
文档注释以名称开头,使用完整句子
行长度约80字符,优先保证可读性
包注释每个包一个,位于
package
语句上方
参数仅文档化非明显行为
Context文档化与隐含行为不符的例外情况
并发文档化不明确的线程安全特性
资源清理必须文档化资源释放要求
错误文档化哨兵值和类型(注意指针)
示例在测试文件中使用可运行示例
格式使用空行分隔段落,缩进表示代码块

See Also

相关链接

  • go-style-core - Core Go style principles and formatting guidelines
  • go-naming - Naming conventions for Go identifiers
  • go-linting - Linting tools for documentation and code quality
  • go-style-core - Go语言核心风格原则与格式规范
  • go-naming - Go标识符命名规范
  • go-linting - 文档与代码质量检查工具