npx skills add https://github.com/cxuu/golang-skills --skill go-documentation本技能涵盖 Google 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) { ...
// 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
}
行为不明显的未导出类型/函数也应具有文档注释。使用相同的风格以便未来轻松导出。
广告位招租
在这里展示您的产品或服务
触达数万 AI 开发者,精准高效
规范性要求:文档注释必须是完整的句子。
首字母大写,以标点符号结尾
例外:如果清晰明了,可以以小写标识符开头
结构体字段的行尾注释可以是短语形式:
// 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)
}
建议性要求:目标约为 80 列,但没有硬性限制。
# 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/
# 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.
根据标点符号进行换行。不要分割长 URL。
规范性要求:每个包必须有且仅有一个包注释。
// Good:
// Package math provides basic constants and mathematical functions.
//
// This package does not guarantee bit-identical results across architectures.
package math
使用二进制名称(与 BUILD 文件匹配):
// 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 文件建议性要求:仅记录容易出错或非显而易见的参数,而非所有内容。
// 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
建议性要求:不要复述隐含的上下文行为;仅记录例外情况。
上下文取消隐含会中断函数并返回 ctx.Err()。不要记录这一点。
// 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
当行为不同时进行记录:
// 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
建议性要求:记录非显而易见的线程安全特性。
只读操作假定是安全的;修改操作假定是不安全的。不要复述这一点。
在以下情况下进行记录:
// 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
}
建议性要求:始终记录显式的清理要求。
// 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)
建议性要求:记录重要的错误哨兵值和类型。
// 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 的正确使用。
对于包范围的错误约定,请在包注释中进行记录。
建议性要求:提供可运行的示例来演示包的用法。
将示例放在测试文件中(*_test.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 语法来获得格式良好的文档。
段落 - 用空行分隔:
// Good:
// LoadConfig reads a configuration out of the named file.
//
// See some/shortlink for config file format details.
逐字/代码块 - 额外缩进两个空格:
// 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 {
// //...
// }
列表和表格 - 使用逐字格式化:
// 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.
标题 - 单行,首字母大写,无标点符号(括号/逗号除外),后跟段落:
// Good:
// Using headings
//
// Headings come with autogenerated anchor tags for easy linking.
建议性要求:当类型本身不够清晰时,用于文档说明。
// 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)
不要仅仅为了启用裸返回而命名结果参数。清晰性 > 简洁性。
建议性要求:添加注释以突出显示不寻常或容易被忽视的模式。
这两者很难区分:
if err := doSomething(); err != nil { // common
// ...
}
if err := doSomething(); err == nil { // unusual!
// ...
}
添加注释以增强信号:
// Good:
if err := doSomething(); err == nil { // if NO error
// ...
}
建议性要求:在代码审查之前和期间预览文档。
go install golang.org/x/pkgsite/cmd/pkgsite@latest
pkgsite
这可以验证 godoc 格式化是否正确渲染。
| 主题 | 关键规则 |
|---|---|
| 文档注释 | 以名称开头,使用完整句子 |
| 行长度 | 约 80 字符,优先考虑可读性 |
| 包注释 | 每个包一个,位于 package 子句上方 |
| 参数 | 仅记录非显而易见的行为 |
| 上下文 | 记录隐含行为的例外情况 |
| 并发性 | 记录模糊的线程安全特性 |
| 清理 | 始终记录资源释放 |
| 错误 | 记录哨兵值和类型(注意指针) |
| 示例 | 在测试文件中使用可运行的示例 |
| 格式化 | 段落用空行,代码用缩进 |
每周安装量
164
代码仓库
GitHub 星标数
35
首次出现
Jan 27, 2026
安全审计
安装于
github-copilot155
codex155
gemini-cli153
kimi-cli152
amp152
opencode152
This skill covers documentation conventions from Google's Go Style Guide.
Normative : All top-level exported names must have doc comments.
// 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) { ...
// 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.
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:
// 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)
}
Advisory : Aim for ~80 columns, but no hard limit.
# 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/
# 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.
Normative : Every package must have exactly one package comment.
// Good:
// Package math provides basic constants and mathematical functions.
//
// This package does not guarantee bit-identical results across architectures.
package math
Use the binary name (matching the BUILD file):
// 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:
doc.go fileAdvisory : Document error-prone or non-obvious parameters, not everything.
// 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
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.
// 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:
// 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
Advisory : Document non-obvious thread safety characteristics.
Read-only operations are assumed safe; mutating operations are assumed unsafe. Don't restate this.
Document when:
// 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
}
Advisory : Always document explicit cleanup requirements.
// 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)
Advisory : Document significant error sentinel values and types.
// 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.
Advisory : Provide runnable examples to demonstrate package usage.
Place examples in test files (*_test.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.
Advisory : Use godoc syntax for well-formatted documentation.
Paragraphs - Separate with blank lines:
// 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:
// 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:
// 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:
// Good:
// Using headings
//
// Headings come with autogenerated anchor tags for easy linking.
Advisory : Use for documentation when types alone aren't clear enough.
// 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.
Advisory : Add comments to highlight unusual or easily-missed patterns.
These two are hard to distinguish:
if err := doSomething(); err != nil { // common
// ...
}
if err := doSomething(); err == nil { // unusual!
// ...
}
Add a comment to boost the signal:
// Good:
if err := doSomething(); err == nil { // if NO error
// ...
}
Advisory : Preview documentation before and during code review.
go install golang.org/x/pkgsite/cmd/pkgsite@latest
pkgsite
This validates godoc formatting renders correctly.
| Topic | Key Rule |
|---|---|
| Doc comments | Start with name, use full sentences |
| Line length | ~80 chars, prioritize readability |
| Package comments | One per package, above package clause |
| Parameters | Document non-obvious behavior only |
| Contexts | Document exceptions to implied behavior |
| Concurrency | Document ambiguous thread safety |
| Cleanup | Always document resource release |
| Errors | Document sentinels and types (note pointer) |
| Examples | Use runnable examples in test files |
| Formatting | Blank lines for paragraphs, indent for code |
Weekly Installs
164
Repository
GitHub Stars
35
First Seen
Jan 27, 2026
Security Audits
Gen Agent Trust HubPassSocketPassSnykPass
Installed on
github-copilot155
codex155
gemini-cli153
kimi-cli152
amp152
opencode152
TypeScript测试神器:Shoehorn迁移指南,告别as断言,实现类型安全测试
764 周安装