| name | go-documentation |
| description | Guidelines for Go documentation including doc comments, package docs, godoc formatting, runnable examples, and signal boosting. Use when writing or reviewing documentation for Go packages, types, functions, or methods. |
Go Documentation
This skill covers documentation conventions from Google's Go Style Guide.
Doc Comments
Normative: All top-level exported names must have doc comments.
Basic Rules
- Begin with the name of the object being described
- An article ("a", "an", "the") may precede the name
- Use full sentences (capitalized, punctuated)
type Request struct { ...
func Encode(w io.Writer, req *Request) { ...
Struct Documentation
type Options struct {
Name string
Group *FooGroup
DB *sql.DB
LargeGroupThreshold int
MinimumMembers int
}
Unexported types/functions with unobvious behavior should also have doc
comments. Use the same style to make future exporting easy.
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:
type Server struct {
BaseDir string
WelcomeMessage string
ProtocolVersion string
PageLength int
}
Comment Line Length
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.
Package Comments
Normative: Every package must have exactly one package comment.
package math
Main Packages
Use the binary name (matching the BUILD file):
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
Parameters and Configuration
Advisory: Document error-prone or non-obvious parameters, not everything.
func Sprintf(format string, data ...any) string
func Sprintf(format string, data ...any) string
Contexts
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.
func (Worker) Run(ctx context.Context) error
func (Worker) Run(ctx context.Context) error
Document when behavior differs:
func (Worker) Run(ctx context.Context) error
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:
func (*Cache) Lookup(key string) (data []byte, ok bool)
func NewFortuneTellerClient(cc *rpc.ClientConn) *FortuneTellerClient
type Watcher interface {
Watch(changed chan<- bool) (unwatch func())
Health() error
}
Cleanup
Advisory: Always document explicit cleanup requirements.
func NewTicker(d Duration) *Ticker
func (c *Client) Get(url string) (resp *Response, err error)
Errors
Advisory: Document significant error sentinel values and types.
func (*File) Read(b []byte) (n int, err error)
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.
Examples
Advisory: Provide runnable examples to demonstrate package usage.
Place examples in test files (*_test.go):
func ExampleConfig_WriteTo() {
cfg := &Config{
Name: "example",
}
if err := cfg.WriteTo(os.Stdout); err != nil {
log.Exitf("Failed to write config: %s", err)
}
}
Examples appear in Godoc attached to the documented element.
Godoc Formatting
Advisory: Use godoc syntax for well-formatted documentation.
Paragraphs - Separate with blank lines:
Verbatim/Code blocks - Indent by two additional spaces:
Lists and tables - Use verbatim formatting:
Headings - Single line, capital letter, no punctuation (except
parens/commas), followed by paragraph:
Named Result Parameters
Advisory: Use for documentation when types alone aren't clear enough.
func (n *Node) Children() (left, right *Node, err error)
func WithTimeout(parent Context, d time.Duration) (ctx Context, cancel func())
func (n *Node) Parent1() (node *Node)
func (n *Node) Parent2() (node *Node, err error)
func (n *Node) Parent1() *Node
func (n *Node) Parent2() (*Node, error)
Don't name results just to enable naked returns. Clarity > brevity.
Signal Boosting
Advisory: Add comments to highlight unusual or easily-missed patterns.
These two are hard to distinguish:
if err := doSomething(); err != nil {
}
if err := doSomething(); err == nil {
}
Add a comment to boost the signal:
if err := doSomething(); err == nil {
}
Documentation Preview
Advisory: Preview documentation before and during code review.
go install golang.org/x/pkgsite/cmd/pkgsite@latest
pkgsite
This validates godoc formatting renders correctly.
Quick Reference
| 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 |
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