Commentary
source ↗Commentary
The conventions around commentary (which include what to comment, what style to use, how to provide runnable examples, etc.) are intended to support the experience of reading the documentation of a public API. See Effective Go for more information.
The best practices document’s section on documentation conventions discusses this further.
Best Practice: Use doc preview during development and code review to see whether the documentation and runnable examples are useful and are presented the way you expect them to be.
Tip: Godoc uses very little special formatting; lists and code snippets should usually be indented to avoid linewrapping. Apart from indentation, decoration should generally be avoided.
Comment line length
There is no fixed line length for comments in Go.
Long comment lines should be wrapped to ensure that source is readable in tools which do not perform automatic wrapping of comment lines. If you are uncertain where to wrap, 80 or 100 columns are common choices. However, this is not a hard cut-off; there are situations where breaking a long literal text is harmful. There is no requirement for the specific column width at which wrapping occurs. Aim to be consistent within a file.
See this post from The Go Blog on documentation for more on commentary.
# 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/Mammalia/Rodentia/Geomyoidea/Geomyidae/
//
// Similarly, if you have other information that is made awkward
// by too many line breaks, use your judgment and include a long line
// if it helps rather than hinders.
Avoid comments that fit large amounts of text onto a single line, which is a poor reader experience.
# Bad:
// This is a comment paragraph. While some code editors and viewers will wrap the paragraph for the reader, others will display a very long line that will overflow most windows and require users to scroll horizontally. In addition, even on a screen capable of displaying the entire line, it is easier to read a narrower paragraph than very wide one.
//
// Don't worry too much about the long URL:
// https://supercalifragilisticexpialidocious.example.com:8080/Animalia/Chordata/Mammalia/Rodentia/Geomyoidea/Geomyidae/
Doc comments
All top-level exported names must have doc comments, as should unexported type or function declarations with unobvious behavior or meaning. These comments should be full sentences that begin with the name of the object being described. An article (“a”, “an”, “the”) can precede the name to make it read more naturally.
// 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) { ...
Doc comments appear in Godoc and are surfaced by IDEs, and therefore should be written for anyone using the package.
A documentation comment applies to the following symbol, or the group of fields if it appears in a struct.
// 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
}
Best Practice: If you have doc comments for unexported code, follow the same custom as if it were exported (namely, starting the comment with the unexported name). This makes it easy to export it later by simply replacing the unexported name with the newly-exported one across both comments and code.
Comment sentences
Comments that are complete sentences should be capitalized and punctuated like standard English sentences. (As an exception, it is okay to begin a sentence with an uncapitalized identifier name if it is otherwise clear. Such cases are probably best done only at the beginning of a paragraph.)
Comments that are sentence fragments have no such requirements for punctuation or capitalization.
Documentation comments should always be complete sentences, and as such should always be capitalized and punctuated. Simple end-of-line comments (especially for struct fields) can be simple phrases that assume the field name is the subject.
// Good:
// A Server handles serving quotes from the collected works of Shakespeare.
type Server struct {
// BaseDir points to the base directory under which Shakespeare's works are stored.
//
// The directory structure is expected to be the following:
// {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 when printing (optional; default: 20)
}
Examples
Packages should clearly document their intended usage. Try to provide a runnable example; examples show up in Godoc. Runnable examples belong in the test file, not the production source file. See this example (Godoc, source).
If it isn’t feasible to provide a runnable example, example code can be provided within code comments. As with other code and command-line snippets in comments, it should follow standard formatting conventions.
Named result parameters
When naming parameters, consider how function signatures appear in Godoc. The name of the function itself and the type of the result parameters are often sufficiently clear.
// Good:
func (n *Node) Parent1() *Node
func (n *Node) Parent2() (*Node, error)
If a function returns two or more parameters of the same type, adding names can be useful.
// Good:
func (n *Node) Children() (left, right *Node, err error)
If the caller must take action on particular result parameters, naming them can help suggest what the action is:
// Good:
// WithTimeout returns a context that will be canceled no later than d duration
// from now.
//
// The caller must arrange for the returned cancel function to be called when
// the context is no longer needed to prevent a resource leak.
func WithTimeout(parent Context, d time.Duration) (ctx Context, cancel func())
In the code above, cancellation is a particular action a caller must take.
However, were the result parameters written as (Context, func()) alone, it
would be unclear what is meant by “cancel function”.
Don’t use named result parameters when the names produce unnecessary repetition.
// Bad:
func (n *Node) Parent1() (node *Node)
func (n *Node) Parent2() (node *Node, err error)
Don’t name result parameters in order to avoid declaring a variable inside the function. This practice results in unnecessary API verbosity at the cost of minor implementation brevity.
Naked returns are acceptable only in a small function. Once it’s a medium-sized function, be explicit with your returned values. Similarly, do not name result parameters just because it enables you to use naked returns. Clarity is always more important than saving a few lines in your function.
It is always acceptable to name a result parameter if its value must be changed in a deferred closure.
Tip: Types can often be clearer than names in function signatures. GoTip #38: Functions as Named Types demonstrates this.
In,
WithTimeoutabove, the real code uses aCancelFuncinstead of a rawfunc()in the result parameter list and requires little effort to document.
Package comments
Package comments must appear immediately above the package clause with no blank line between the comment and the package name. Example:
// Good:
// Package math provides basic constants and mathematical functions.
//
// This package does not guarantee bit-identical results across architectures.
package math
There must be a single package comment per package. If a package is composed of multiple files, exactly one of the files should have a package comment.
Comments for main packages have a slightly different form, where the name of
the go_binary rule in the BUILD file takes the place of the package name.
// Good:
// The seed_generator command is a utility that generates a Finch seed file
// from a set of JSON study configs.
package main
Other styles of comment are fine as long as the name of the binary is exactly as written in the BUILD file. When the binary name is the first word, capitalizing it is required even though it does not strictly match the spelling of the command-line invocation.
// Good:
// Binary seed_generator ...
// Command seed_generator ...
// Program seed_generator ...
// The seed_generator command ...
// The seed_generator program ...
// Seed_generator ...
Tips:
-
Example command-line invocations and API usage can be useful documentation. For Godoc formatting, indent the comment lines containing code.
-
If there is no obvious primary file or if the package comment is extraordinarily long, it is acceptable to put the doc comment in a file named
doc.gowith only the comment and the package clause. -
Multiline comments can be used instead of multiple single-line comments. This is primarily useful if the documentation contains sections which may be useful to copy and paste from the source file, as with sample command-lines (for binaries) and template examples.
// Good: /* The seed_generator command is a utility that generates a Finch seed file from a set of JSON study configs. seed_generator *.json | base64 > finch-seed.base64 */ package template -
Comments intended for maintainers and that apply to the whole file are typically placed after import declarations. These are not surfaced in Godoc and are not subject to the rules above on package comments.