Go 文档注释
目录
“文档注释”是紧接在顶层包、常量、函数、类型和变量声明之前,且中间没有换行符的注释。每个导出的(大写字母开头的)名称都应该有文档注释。
go/doc 和 go/doc/comment 包提供了从 Go 源代码中提取文档的功能,并且各种工具都利用了这一功能。go
doc
命令查找并打印给定包或符号的文档注释。(符号是顶层常量、函数、类型或变量。)网络服务器 pkg.go.dev 显示公共 Go 包的文档(在其许可证允许的情况下)。服务该网站的程序是 golang.org/x/pkgsite/cmd/pkgsite,也可以在本地运行以查看私有模块的文档或在没有互联网连接的情况下使用。语言服务器 gopls 在 IDE 中编辑 Go 源文件时提供文档。
本页的其余部分介绍了如何编写 Go 文档注释。
软件包
每个包都应该有一个包注释来介绍该包。它提供与整个包相关的信息,并通常为包设定预期。特别是在大型包中,包注释提供 API 最重要部分的简要概述,并根据需要链接到其他文档注释,可能会有所帮助。
如果包很简单,包注释可以很简短。例如:
// Package path implements utility routines for manipulating slash-separated
// paths.
//
// The path package should only be used for paths separated by forward
// slashes, such as the paths in URLs. This package does not deal with
// Windows paths with drive letters or backslashes; to manipulate
// operating system paths, use the [path/filepath] package.
package path
[path/filepath]
中的方括号会创建一个文档链接。
如本例所示,Go 文档注释使用完整的句子。对于包注释,这意味着第一个句子以“Package”开头。
对于多文件包,包注释只能在一个源文件中。如果多个文件有包注释,它们将被连接起来形成整个包的一个大注释。
命令
命令的包注释与此类似,但它描述的是程序的行为,而不是包中的 Go 符号。第一个句子通常以程序本身的名称开头,大写,因为它位于句子的开头。例如,这是 gofmt 的包注释的删节版本:
/*
Gofmt formats Go programs.
It uses tabs for indentation and blanks for alignment.
Alignment assumes that an editor is using a fixed-width font.
Without an explicit path, it processes the standard input. Given a file,
it operates on that file; given a directory, it operates on all .go files in
that directory, recursively. (Files starting with a period are ignored.)
By default, gofmt prints the reformatted sources to standard output.
Usage:
gofmt [flags] [path ...]
The flags are:
-d
Do not print reformatted sources to standard output.
If a file's formatting is different than gofmt's, print diffs
to standard output.
-w
Do not print reformatted sources to standard output.
If a file's formatting is different from gofmt's, overwrite it
with gofmt's version. If an error occurred during overwriting,
the original file is restored from an automatic backup.
When gofmt reads from standard input, it accepts either a full Go program
or a program fragment. A program fragment must be a syntactically
valid declaration list, statement list, or expression. When formatting
such a fragment, gofmt preserves leading indentation as well as leading
and trailing spaces, so that individual sections of a Go program can be
formatted by piping them through gofmt.
*/
package main
注释的开头使用语义换行符编写,其中每个新句子或长短语都单独占一行,这使得代码和注释演进时,差异更容易阅读。后面的段落恰好没有遵循这个约定,而是手工换行了。只要最适合您的代码库即可。无论哪种方式,go
doc
和 pkgsite
在打印时都会重新包装文档注释文本。例如:
$ go doc gofmt
Gofmt formats Go programs. It uses tabs for indentation and blanks for
alignment. Alignment assumes that an editor is using a fixed-width font.
Without an explicit path, it processes the standard input. Given a file, it
operates on that file; given a directory, it operates on all .go files in that
directory, recursively. (Files starting with a period are ignored.) By default,
gofmt prints the reformatted sources to standard output.
Usage:
gofmt [flags] [path ...]
The flags are:
-d
Do not print reformatted sources to standard output.
If a file's formatting is different than gofmt's, print diffs
to standard output.
...
缩进的行被视为预格式化文本:它们不会被重新包装,并且在 HTML 和 Markdown 演示文稿中以代码字体打印。(下面的语法部分提供了详细信息。)
类型
类型的文档注释应解释该类型的每个实例代表或提供什么。如果 API 简单,文档注释可以非常简短。例如:
package zip
// A Reader serves content from a ZIP archive.
type Reader struct {
...
}
默认情况下,程序员应期望类型一次只能由一个 goroutine 安全使用。如果类型提供更强的保证,文档注释应予以说明。例如:
package regexp
// Regexp is the representation of a compiled regular expression.
// A Regexp is safe for concurrent use by multiple goroutines,
// except for configuration methods, such as Longest.
type Regexp struct {
...
}
Go 类型还应该力求使零值具有有用的含义。如果含义不明显,则应予以文档说明。例如:
package bytes
// A Buffer is a variable-sized buffer of bytes with Read and Write methods.
// The zero value for Buffer is an empty buffer ready to use.
type Buffer struct {
...
}
对于带有导出字段的结构体,文档注释或逐字段注释应解释每个导出字段的含义。例如,此类型的文档注释解释了这些字段:
package io
// A LimitedReader reads from R but limits the amount of
// data returned to just N bytes. Each call to Read
// updates N to reflect the new amount remaining.
// Read returns EOF when N <= 0.
type LimitedReader struct {
R Reader // underlying reader
N int64 // max bytes remaining
}
相反,此类型的文档注释将解释留给逐字段注释:
package comment
// A Printer is a doc comment printer.
// The fields in the struct can be filled in before calling
// any of the printing methods
// in order to customize the details of the printing process.
type Printer struct {
// HeadingLevel is the nesting level used for
// HTML and Markdown headings.
// If HeadingLevel is zero, it defaults to level 3,
// meaning to use <h3> and ###.
HeadingLevel int
...
}
与包(上文)和函数(下文)一样,类型的文档注释以完整的句子开头,并命名所声明的符号。明确的主语通常使措辞更清晰,并使文本更容易搜索,无论是在网页上还是在命令行上。例如:
$ go doc -all regexp | grep pairs
pairs within the input string: result[2*n:2*n+2] identifies the indexes
FindReaderSubmatchIndex returns a slice holding the index pairs identifying
FindStringSubmatchIndex returns a slice holding the index pairs identifying
FindSubmatchIndex returns a slice holding the index pairs identifying the
$
函数
函数的文档注释应解释函数返回什么,或者对于因副作用而调用的函数,它做什么。命名参数和结果可以直接在注释中引用,无需任何特殊语法,例如反引号。(这一约定的结果是,通常会避免使用诸如 a
之类的可能被误认为是普通单词的名称。)例如:
package strconv
// Quote returns a double-quoted Go string literal representing s.
// The returned string uses Go escape sequences (\t, \n, \xFF, \u0100)
// for control characters and non-printable characters as defined by IsPrint.
func Quote(s string) string {
...
}
和
package os
// Exit causes the current program to exit with the given status code.
// Conventionally, code zero indicates success, non-zero an error.
// The program terminates immediately; deferred functions are not run.
//
// For portability, the status code should be in the range [0, 125].
func Exit(code int) {
...
}
文档注释通常使用“reports whether”来描述返回布尔值的函数。“or not”这个短语是不必要的。例如:
package strings
// HasPrefix reports whether the string s begins with prefix.
func HasPrefix(s, prefix string) bool
如果文档注释需要解释多个结果,命名结果可以使文档注释更容易理解,即使这些名称没有在函数体中使用。例如:
package io
// Copy copies from src to dst until either EOF is reached
// on src or an error occurs. It returns the total number of bytes
// written and the first error encountered while copying, if any.
//
// A successful Copy returns err == nil, not err == EOF.
// Because Copy is defined to read from src until EOF, it does
// not treat an EOF from Read as an error to be reported.
func Copy(dst Writer, src Reader) (n int64, err error) {
...
}
反之,当结果不需要在文档注释中命名时,它们通常在代码中也省略,如上面的 Quote
示例所示,以避免混淆展示。
这些规则都适用于普通函数和方法。对于方法,使用相同的接收器名称可以避免在列出类型所有方法时出现不必要的差异:
$ go doc bytes.Buffer
package bytes // import "bytes"
type Buffer struct {
// Has unexported fields.
}
A Buffer is a variable-sized buffer of bytes with Read and Write methods.
The zero value for Buffer is an empty buffer ready to use.
func NewBuffer(buf []byte) *Buffer
func NewBufferString(s string) *Buffer
func (b *Buffer) Bytes() []byte
func (b *Buffer) Cap() int
func (b *Buffer) Grow(n int)
func (b *Buffer) Len() int
func (b *Buffer) Next(n int) []byte
func (b *Buffer) Read(p []byte) (n int, err error)
func (b *Buffer) ReadByte() (byte, error)
...
此示例还表明,返回类型 T
或指针 *T
的顶级函数,可能带有额外的错误结果,会与类型 T
及其方法一起显示,假设它们是 T
的构造函数。
默认情况下,程序员可以假设顶级函数可以安全地从多个 goroutine 调用;这个事实无需明确说明。
另一方面,如前一节所述,以任何方式使用类型实例,包括调用方法,通常假定一次仅限于单个 goroutine。如果并发安全使用的方法未在类型的文档注释中说明,则应在逐方法注释中说明。例如:
package sql
// Close returns the connection to the connection pool.
// All operations after a Close will return with ErrConnDone.
// Close is safe to call concurrently with other operations and will
// block until all other operations finish. It may be useful to first
// cancel any used context and then call Close directly after.
func (c *Conn) Close() error {
...
}
请注意,函数和方法的文档注释侧重于操作返回或做什么,详细说明调用者需要知道什么。特殊情况可能尤其需要文档说明。例如:
package math
// Sqrt returns the square root of x.
//
// Special cases are:
//
// Sqrt(+Inf) = +Inf
// Sqrt(±0) = ±0
// Sqrt(x < 0) = NaN
// Sqrt(NaN) = NaN
func Sqrt(x float64) float64 {
...
}
文档注释不应解释内部细节,例如当前实现中使用的算法。这些最好留在函数体内的注释中。当该细节对调用者特别重要时,提供渐近时间或空间边界可能是合适的。例如:
package sort
// Sort sorts data in ascending order as determined by the Less method.
// It makes one call to data.Len to determine n and O(n*log(n)) calls to
// data.Less and data.Swap. The sort is not guaranteed to be stable.
func Sort(data Interface) {
...
}
因为这个文档注释没有提及使用哪种排序算法,所以将来更容易更改实现以使用不同的算法。
常量
Go 的声明语法允许声明分组,在这种情况下,单个文档注释可以介绍一组相关的常量,而单个常量仅由简短的行尾注释文档说明。例如:
package scanner // import "text/scanner"
// The result of Scan is one of these tokens or a Unicode character.
const (
EOF = -(iota + 1)
Ident
Int
Float
Char
...
)
有时,该组根本不需要文档注释。例如:
package unicode // import "unicode"
const (
MaxRune = '\U0010FFFF' // maximum valid Unicode code point.
ReplacementChar = '\uFFFD' // represents invalid code points.
MaxASCII = '\u007F' // maximum ASCII value.
MaxLatin1 = '\u00FF' // maximum Latin-1 value.
)
另一方面,未分组的常量通常需要一个以完整句子开头的完整文档注释。例如:
package unicode
// Version is the Unicode edition from which the tables are derived.
const Version = "13.0.0"
类型常量显示在其类型声明旁边,因此通常省略常量组文档注释,而倾向于类型的文档注释。例如:
package syntax
// An Op is a single regular expression operator.
type Op uint8
const (
OpNoMatch Op = 1 + iota // matches no strings
OpEmptyMatch // matches empty string
OpLiteral // matches Runes sequence
OpCharClass // matches Runes interpreted as range pair list
OpAnyCharNotNL // matches any character except newline
...
)
(请参阅 pkg.go.dev/regexp/syntax#Op 以获取 HTML 呈现。)
变量
变量的约定与常量的约定相同。例如,这是一组分组变量:
package fs
// Generic file system errors.
// Errors returned by file systems can be tested against these errors
// using errors.Is.
var (
ErrInvalid = errInvalid() // "invalid argument"
ErrPermission = errPermission() // "permission denied"
ErrExist = errExist() // "file already exists"
ErrNotExist = errNotExist() // "file does not exist"
ErrClosed = errClosed() // "file already closed"
)
以及单个变量:
package unicode
// Scripts is the set of Unicode script tables.
var Scripts = map[string]*RangeTable{
"Adlam": Adlam,
"Ahom": Ahom,
"Anatolian_Hieroglyphs": Anatolian_Hieroglyphs,
"Arabic": Arabic,
"Armenian": Armenian,
...
}
语法
Go 文档注释使用一种简单的语法编写,支持段落、标题、链接、列表和预格式化代码块。为了使注释在源文件中轻量且可读,不支持字体更改或原始 HTML 等复杂功能。Markdown 爱好者可以将该语法视为 Markdown 的简化子集。
标准格式化程序 gofmt 会重新格式化文档注释,使其对每个功能都使用规范的格式。Gofmt 旨在提高可读性和用户对如何在源代码中编写注释的控制,但会调整呈现以使特定注释的语义含义更清晰,类似于在普通源代码中将 1+2 * 3
重新格式化为 1 + 2*3
。
诸如 //go:generate
之类的指令注释不被视为文档注释的一部分,并从渲染的文档中省略。Gofmt 将指令注释移到文档注释的末尾,前面是一个空行。例如:
package regexp
// An Op is a single regular expression operator.
//
//go:generate stringer -type Op -trimprefix Op
type Op uint8
指令注释是匹配正则表达式 //(line |extern |export |[a-z0-9]+:[a-z0-9])
的行。定义自己指令的工具应使用 //toolname:directive
形式。
Gofmt 会删除文档注释中的前导和尾随空行。如果文档注释中的所有行都以相同的空格和制表符序列开头,gofmt 会删除该前缀。
段落
段落是一段未缩进的非空行。我们已经看到了许多段落的例子。
一对连续的反引号 (` U+0060) 被解释为 Unicode 左引号 (“ U+201C),一对连续的单引号 (' U+0027) 被解释为 Unicode 右引号 (” U+201D)。
Gofmt 保留段落文本中的换行符:它不会重新换行文本。这允许使用语义换行符,如前所述。Gofmt 用单个空行替换段落之间重复的空行。Gofmt 还会将连续的反引号或单引号重新格式化为其 Unicode 解释。
注意事项
备注是特殊注释,形式为 MARKER(uid): body
。MARKER 应由 2 个或更多大写 [A-Z]
字母组成,用于标识备注的类型,而 uid 至少有 1 个字符,通常是提供更多信息的人的用户名。uid 后面的 :
是可选的。
备注会在 pkg.go.dev 上收集并以单独的部分呈现。
例如
// TODO(user1): refactor to use standard library context
// BUG(user2): not cleaned up
var ctx context.Context
弃用
以 Deprecated:
开头的段落被视为弃用通知。某些工具会在使用已弃用标识符时发出警告。pkg.go.dev 默认会隐藏其文档。
弃用通知后会提供有关弃用的信息,以及(如果适用)关于替代方案的建议。该段落不必是文档注释中的最后一段。
例如
// Package rc4 implements the RC4 stream cipher.
//
// Deprecated: RC4 is cryptographically broken and should not be used
// except for compatibility with legacy systems.
//
// This package is frozen and no new functionality will be added.
package rc4
// Reset zeros the key data and makes the Cipher unusable.
//
// Deprecated: Reset can't guarantee that the key will be entirely removed from
// the process's memory.
func (c *Cipher) Reset()
标题
标题是一行,以井号 (# U+0023) 开头,后跟一个空格和标题文本。要被识别为标题,该行必须不缩进,并与相邻的段落文本用空行隔开。
例如
// Package strconv implements conversions to and from string representations
// of basic data types.
//
// # Numeric Conversions
//
// The most common numeric conversions are [Atoi] (string to int) and [Itoa] (int to string).
...
package strconv
另一方面
// #This is not a heading, because there is no space.
//
// # This is not a heading,
// # because it is multiple lines.
//
// # This is not a heading,
// because it is also multiple lines.
//
// The next paragraph is not a heading, because there is no additional text:
//
// #
//
// In the middle of a span of non-blank lines,
// # this is not a heading either.
//
// # This is not a heading, because it is indented.
# 语法是在 Go 1.19 中添加的。在 Go 1.19 之前,标题是通过满足某些条件(最值得注意的是没有终止标点符号)的单行段落隐式识别的。
Gofmt 会将早期 Go 版本中被视为隐式标题的行重新格式化为使用 # 标题。如果重新格式化不合适——也就是说,如果该行并非旨在作为标题——最简单的方法是引入终止标点符号(例如句号或冒号),或者将其拆分成两行,使其成为一个段落。
链接
当每一行都采用“[Text]: URL”的形式时,一段不缩进的非空行定义了链接目标。在同一文档注释中的其他文本中,“[Text]”表示使用给定文本链接到 URL——在 HTML 中,Text。例如:
// Package json implements encoding and decoding of JSON as defined in
// [RFC 7159]. The mapping between JSON and Go values is described
// in the documentation for the Marshal and Unmarshal functions.
//
// For an introduction to this package, see the article
// “[JSON and Go].”
//
// [RFC 7159]: https://tools.ietf.org/html/rfc7159
// [JSON and Go]: https://golang.ac.cn/doc/articles/json_and_go.html
package json
通过将 URL 放在单独的部分,这种格式只会最大限度地打断实际文本的流畅性。它也大致符合 Markdown 快捷引用链接格式,不包含可选的标题文本。
如果不存在对应的 URL 声明,那么(除了下一节描述的文档链接)“[Text]”就不是超链接,并且方括号在显示时会保留。每个文档注释都是独立考虑的:一个注释中的链接目标定义不影响其他注释。
虽然链接目标定义块可以与普通段落交错,但 gofmt 会将所有链接目标定义移动到文档注释的末尾,最多分成两个块:第一个块包含注释中引用的所有链接目标,然后是包含注释中*未*引用的所有目标的块。单独的块使得未使用的目标易于发现和修复(如果链接或定义有拼写错误)或删除(如果定义不再需要)。
被识别为 URL 的纯文本会在 HTML 渲染中自动链接。
文档链接
文档链接的形式为“[Name1]”或“[Name1.Name2]”,用于引用当前包中导出的标识符;或者“[pkg]”、“[pkg.Name1]”或“[pkg.Name1.Name2]”,用于引用其他包中的标识符。
例如
package bytes
// ReadFrom reads data from r until EOF and appends it to the buffer, growing
// the buffer as needed. The return value n is the number of bytes read. Any
// error except [io.EOF] encountered during the read is also returned. If the
// buffer becomes too large, ReadFrom will panic with [ErrTooLarge].
func (b *Buffer) ReadFrom(r io.Reader) (n int64, err error) {
...
}
符号链接的方括号文本可以包含可选的前导星号,以便于引用指针类型,例如 [*bytes.Buffer]。
在引用其他包时,“pkg”可以是完整的导入路径,也可以是现有导入的假定包名。假定包名要么是重命名导入中的标识符,要么是 goimports 所假定的名称。(Goimports 会在假定不正确时插入重命名,因此此规则应适用于所有 Go 代码。)例如,如果当前包导入 encoding/json,那么 “[json.Decoder]” 可以代替 “[encoding/json.Decoder]” 链接到 encoding/json 的 Decoder 文档。如果包中的不同源文件使用相同的名称导入不同的包,则缩写会产生歧义,无法使用。
“pkg”仅在以域名(带有点的路径元素)开头或属于标准库包(“[os]”、“[encoding/json]”等)时才被假定为完整的导入路径。例如,[os.File]
和 [example.com/sys.File]
是文档链接(后者将是断开的链接),但 [os/sys.File]
不是,因为标准库中没有 os/sys 包。
为了避免与映射、泛型和数组类型相关的问题,文档链接必须在前后都带有标点符号、空格、制表符或行首行尾。例如,文本“map[ast.Expr]TypeAndValue”不包含文档链接。
列表
列表是一段缩进或空行(否则将是代码块,如下一节所述),其中第一行缩进行以项目符号列表标记或编号列表标记开头。
项目符号列表标记是一个星号、加号、破折号或 Unicode 项目符号(*、+、-、•;U+002A、U+002B、U+002D、U+2022),后跟一个空格或制表符,然后是文本。在项目符号列表中,每行以项目符号列表标记开头都会开始一个新列表项。
例如
package url
// PublicSuffixList provides the public suffix of a domain. For example:
// - the public suffix of "example.com" is "com",
// - the public suffix of "foo1.foo2.foo3.co.uk" is "co.uk", and
// - the public suffix of "bar.pvt.k12.ma.us" is "pvt.k12.ma.us".
//
// Implementations of PublicSuffixList must be safe for concurrent use by
// multiple goroutines.
//
// An implementation that always returns "" is valid and may be useful for
// testing but it is not secure: it means that the HTTP server for foo.com can
// set a cookie for bar.com.
//
// A public suffix list implementation is in the package
// golang.org/x/net/publicsuffix.
type PublicSuffixList interface {
...
}
编号列表标记是任意长度的十进制数字,后跟一个句点或右括号,然后是一个空格或制表符,然后是文本。在编号列表中,每行以编号列表标记开头都会开始一个新列表项。项目编号保持不变,从不重新编号。
例如
package path
// Clean returns the shortest path name equivalent to path
// by purely lexical processing. It applies the following rules
// iteratively until no further processing can be done:
//
// 1. Replace multiple slashes with a single slash.
// 2. Eliminate each . path name element (the current directory).
// 3. Eliminate each inner .. path name element (the parent directory)
// along with the non-.. element that precedes it.
// 4. Eliminate .. elements that begin a rooted path:
// that is, replace "/.." by "/" at the beginning of a path.
//
// The returned path ends in a slash only if it is the root "/".
//
// If the result of this process is an empty string, Clean
// returns the string ".".
//
// See also Rob Pike, “[Lexical File Names in Plan 9].”
//
// [Lexical File Names in Plan 9]: https://9p.io/sys/doc/lexnames.html
func Clean(path string) string {
...
}
列表项只包含段落,不包含代码块或嵌套列表。这避免了任何关于空格计数的细微差别以及关于制表符在不一致缩进中计为多少空格的问题。
Gofmt 会将项目符号列表重新格式化为使用破折号作为项目符号标记,破折号前缩进两个空格,以及连续行缩进四个空格。
Gofmt 会将编号列表重新格式化为在数字前使用一个空格,数字后使用一个句点,以及连续行再次缩进四个空格。
Gofmt 保留但不要求列表和前一个段落之间有一个空行。它会在列表和后续段落或标题之间插入一个空行。
代码块
代码块是一段缩进或空行,不以项目符号列表标记或编号列表标记开头。它被渲染为预格式化文本(HTML 中的
块)。代码块通常包含 Go 代码。例如:
package sort // Search uses binary search... // // As a more whimsical example, this program guesses your number: // // func GuessingGame() { // var s string // fmt.Printf("Pick an integer from 0 to 100.\n") // answer := sort.Search(100, func(i int) bool { // fmt.Printf("Is your number <= %d? ", i) // fmt.Scanf("%s", &s) // return s != "" && s[0] == 'y' // }) // fmt.Printf("Your number is %d.\n", answer) // } func Search(n int, f func(int) bool) int { ... }
当然,代码块除了代码之外,也常常包含预格式化文本。例如:
package path // Match reports whether name matches the shell pattern. // The pattern syntax is: // // pattern: // { term } // term: // '*' matches any sequence of non-/ characters // '?' matches any single non-/ character // '[' [ '^' ] { character-range } ']' // character class (must be non-empty) // c matches character c (c != '*', '?', '\\', '[') // '\\' c matches character c // // character-range: // c matches character c (c != '\\', '-', ']') // '\\' c matches character c // lo '-' hi matches character c for lo <= c <= hi // // Match requires pattern to match all of name, not just a substring. // The only possible returned error is [ErrBadPattern], when pattern // is malformed. func Match(pattern, name string) (matched bool, err error) { ... }
Gofmt 会将代码块中的所有行缩进一个制表符,替换非空行共有的任何其他缩进。Gofmt 还会为每个代码块的前后插入一个空行,从而将代码块与周围的段落文本明确区分开来。
常见错误和陷阱
Go 最早的时候就规定,文档注释中任何一段缩进或空行都将渲染为代码块。不幸的是,gofmt 缺乏对文档注释的支持,导致许多现有注释使用缩进却并非旨在创建代码块。
例如,这个未缩进的列表一直被 godoc 解释为一个三行段落,后跟一个单行代码块:
package http // cancelTimerBody is an io.ReadCloser that wraps rc with two features: // 1) On Read error or close, the stop func is called. // 2) On Read failure, if reqDidTimeout is true, the error is wrapped and // marked as net.Error that hit its timeout. type cancelTimerBody struct { ... }
这总是在
go
doc
中呈现为:cancelTimerBody is an io.ReadCloser that wraps rc with two features: 1) On Read error or close, the stop func is called. 2) On Read failure, if reqDidTimeout is true, the error is wrapped and marked as net.Error that hit its timeout.
同样,此注释中的命令是一个单行段落,后跟一个单行代码块:
package smtp // localhostCert is a PEM-encoded TLS cert generated from src/crypto/tls: // // go run generate_cert.go --rsa-bits 1024 --host 127.0.0.1,::1,example.com \ // --ca --start-date "Jan 1 00:00:00 1970" --duration=1000000h var localhostCert = []byte(`...`)
这在
go
doc
中呈现为:localhostCert is a PEM-encoded TLS cert generated from src/crypto/tls: go run generate_cert.go --rsa-bits 1024 --host 127.0.0.1,::1,example.com \ --ca --start-date "Jan 1 00:00:00 1970" --duration=1000000h
而这个注释是一个两行段落(第二行是“{”),后跟一个六行缩进代码块和一个单行段落(“}”)。
// On the wire, the JSON will look something like this: // { // "kind":"MyAPIObject", // "apiVersion":"v1", // "myPlugin": { // "kind":"PluginA", // "aOption":"foo", // }, // }
这在
go
doc
中呈现为:On the wire, the JSON will look something like this: { "kind":"MyAPIObject", "apiVersion":"v1", "myPlugin": { "kind":"PluginA", "aOption":"foo", }, }
另一个常见错误是未缩进的 Go 函数定义或块语句,同样用“{”和“}”括起来。
Go 1.19 的 gofmt 引入了文档注释重新格式化功能,通过在代码块周围添加空行,使这些错误更加明显。
2022 年的分析发现,公共 Go 模块中只有 3% 的文档注释被 Go 1.19 gofmt 草稿重新格式化过。仅限于这些注释,大约 87% 的 gofmt 重新格式化保留了人们通过阅读注释推断出的结构;大约 6% 被这些未缩进的列表、未缩进的多行 shell 命令和未缩进的大括号分隔的代码块所困扰。
基于此分析,Go 1.19 gofmt 采用了一些启发式方法将未缩进的行合并到相邻的缩进列表或代码块中。经过这些调整,Go 1.19 gofmt 将上述示例重新格式化为:
// cancelTimerBody is an io.ReadCloser that wraps rc with two features: // 1. On Read error or close, the stop func is called. // 2. On Read failure, if reqDidTimeout is true, the error is wrapped and // marked as net.Error that hit its timeout. // localhostCert is a PEM-encoded TLS cert generated from src/crypto/tls: // // go run generate_cert.go --rsa-bits 1024 --host 127.0.0.1,::1,example.com \ // --ca --start-date "Jan 1 00:00:00 1970" --duration=1000000h // On the wire, the JSON will look something like this: // // { // "kind":"MyAPIObject", // "apiVersion":"v1", // "myPlugin": { // "kind":"PluginA", // "aOption":"foo", // }, // }
这种重新格式化使含义更清晰,并使文档注释在早期 Go 版本中正确渲染。如果启发式方法做出错误的决策,可以通过插入空行来明确将段落文本与非段落文本分开来覆盖它。
即使有了这些启发式方法,其他现有注释仍需要手动调整以纠正其渲染。最常见的错误是缩进换行的未缩进行文本。例如:
// TODO Revisit this design. It may make sense to walk those nodes // only once. // According to the document: // "The alignment factor (in bytes) that is used to align the raw data of sections in // the image file. The value should be a power of 2 between 512 and 64 K, inclusive."
在这两者中,最后一行都缩进了,使其成为代码块。修复方法是取消缩进这些行。
另一个常见错误是没有缩进列表或代码块中换行的缩进行。例如:
// Uses of this error model include: // // - Partial errors. If a service needs to return partial errors to the // client, // it may embed the `Status` in the normal response to indicate the // partial // errors. // // - Workflow errors. A typical workflow has multiple steps. Each step // may // have a `Status` message for error reporting.
解决方法是缩进换行的行。
Go 文档注释不支持嵌套列表,因此 gofmt 会将
// Here is a list: // // - Item 1. // * Subitem 1. // * Subitem 2. // - Item 2. // - Item 3.
转换为
// Here is a list: // // - Item 1. // - Subitem 1. // - Subitem 2. // - Item 2. // - Item 3.
重写文本以避免嵌套列表通常会改善文档,并且是最佳解决方案。另一个潜在的变通方法是混合使用列表标记,因为项目符号标记不会在编号列表中引入列表项,反之亦然。例如:
// Here is a list: // // 1. Item 1. // // - Subitem 1. // // - Subitem 2. // // 2. Item 2. // // 3. Item 3.