Comments and documentation
suggest changeGo has two kinds of comments, and a convention that turns some of them into documentation. A comment placed right before a top-level declaration is a doc comment. go doc, pkg.go.dev and editors (through gopls) read doc comments and show them as the package's documentation. You don't need a separate tool or special markup like Javadoc's @param.
Comment syntax
package main
import "fmt"
/*
A block comment can span
multiple lines.
*/
func main() {
// A line comment runs to the end of the line.
x := 10 // it can follow code on the same line
y := /* or sit inside an expression */ 20
// Comment markers inside string literals are just text.
s := "// not a comment"
r := `/* not a comment either */`
fmt.Println(x + y)
fmt.Println(s)
fmt.Println(r)
}
30
// not a comment
/* not a comment either */
Block comments don't nest. The first */ ends the comment, so this doesn't compile:
/* outer /* inner */ still outer? */
func main() {}
nest\main.go:3:22: syntax error: non-declaration statement outside function body
nest\main.go:3:33: invalid character U+003F '?'
Idiomatic Go uses // almost everywhere, including for doc comments. /* */ is mostly used to temporarily disable a chunk of code, or for license headers.
Doc comments
A doc comment is a comment that appears directly before a top-level package, const, func, type or var declaration, with no blank line in between. Doc comments matter most for exported (capitalized) names, because those make up the package's API.
The rules are short:
- Write complete sentences.
- Start with the name of the thing you're documenting: "Parse parses...", "Celsius is...", "ErrNotFound is returned when...".
- Say what the thing does and what it returns, not how it works inside.
Starting with the name reads well in the generated docs, and it makes go doc -all pkg | grep Name useful.
Here's a small package that we'll use for the rest of the article. It has a separate doc.go file that holds the package comment:
temp/doc.go:
// Package temp converts between temperature scales.
//
// Temperatures are stored as [Celsius] values. Use [FromFahrenheit]
// and [Celsius.Fahrenheit] to convert to and from the Fahrenheit scale.
//
// # Precision
//
// All conversions use float64 arithmetic, so results may differ
// from exact values in the last few bits. See [math.Round] if you
// need to round for display.
//
// The scales are described on [Wikipedia].
//
// [Wikipedia]: https://en.wikipedia.org/wiki/Temperature
package temp
temp/temp.go:
package temp
import (
"errors"
"fmt"
)
// Celsius is a temperature in degrees Celsius.
type Celsius float64
// Common reference temperatures.
const (
Freezing Celsius = 0 // water freezes
Boiling Celsius = 100 // water boils at sea level
)
// AbsoluteZero is the lowest possible temperature.
const AbsoluteZero Celsius = -273.15
// ErrBelowAbsoluteZero is returned by [Parse] when the value is
// colder than [AbsoluteZero].
var ErrBelowAbsoluteZero = errors.New("temp: below absolute zero")
// FromFahrenheit returns the Celsius equivalent of f degrees Fahrenheit.
func FromFahrenheit(f float64) Celsius {
return Celsius((f - 32) * 5 / 9)
}
// Fahrenheit returns c converted to degrees Fahrenheit.
func (c Celsius) Fahrenheit() float64 {
return float64(c)*9/5 + 32
}
// String formats c with one decimal place, for example "21.5°C".
// It implements [fmt.Stringer].
func (c Celsius) String() string {
return fmt.Sprintf("%.1f°C", float64(c))
}
// Parse parses s, a number optionally followed by "C" or "F".
// Values without a suffix are treated as Celsius.
//
// Parse returns an error if s is malformed or if the temperature
// is below [AbsoluteZero]:
//
// t, err := temp.Parse("451F")
// if err != nil {
// log.Fatal(err)
// }
// fmt.Println(t) // 232.8°C
func Parse(s string) (Celsius, error) {
var v float64
var unit string
n, err := fmt.Sscanf(s, "%g%s", &v, &unit)
if n == 0 {
return 0, fmt.Errorf("temp: invalid temperature %q: %w", s, err)
}
var c Celsius
switch unit {
case "", "C":
c = Celsius(v)
case "F":
c = FromFahrenheit(v)
default:
return 0, fmt.Errorf("temp: unknown unit %q", unit)
}
if c < AbsoluteZero {
return 0, ErrBelowAbsoluteZero
}
return c, nil
}
// Kelvin returns c in kelvins.
//
// Deprecated: Use [Celsius.Kelvin] instead.
func Kelvin(c Celsius) float64 {
return c.Kelvin()
}
// Kelvin returns c in kelvins.
func (c Celsius) Kelvin() float64 {
return float64(c - AbsoluteZero)
}
// BUG(kjk): Parse does not accept the "K" suffix for kelvins.
A few things to notice:
- Package comment. It starts with "Package temp" and comes before the
packageclause. Only one file in the package should have it. For short packages, put it in the main file. For long ones, adoc.gofile that holds only the package comment is the convention. - Grouped declarations. The comment before
const (documents the whole group. The trailing// water freezescomments also show up in the docs, becausego docprints the group's source. - Methods are documented like functions. They show up under their type.
When the package is used, the comments do nothing at run time, of course:
package main
import (
"fmt"
"log"
"example.com/weather/temp"
)
func main() {
t, err := temp.Parse("451F")
if err != nil {
log.Fatal(err)
}
fmt.Println(t)
fmt.Println(temp.Boiling.Fahrenheit())
fmt.Printf("%.2f\n", temp.Freezing.Kelvin())
_, err = temp.Parse("-500")
fmt.Println(err)
}
232.8°C
212
273.15
temp: below absolute zero
Reading docs with go doc
go doc prints documentation from source in your terminal. With a package argument it shows the package comment and a summary of exported names:
$ go doc ./temp
package temp // import "example.com/weather/temp"
Package temp converts between temperature scales.
Temperatures are stored as Celsius values. Use FromFahrenheit and
Celsius.Fahrenheit to convert to and from the Fahrenheit scale.
# Precision
All conversions use float64 arithmetic, so results may differ from exact values
in the last few bits. See math.Round if you need to round for display.
The scales are described on Wikipedia.
[Wikipedia]: https://en.wikipedia.org/wiki/Temperature
var ErrBelowAbsoluteZero = errors.New("temp: below absolute zero")
func Kelvin(c Celsius) float64
type Celsius float64
const Freezing Celsius = 0 ...
const AbsoluteZero Celsius = -273.15
func FromFahrenheit(f float64) Celsius
func Parse(s string) (Celsius, error)
BUG: Parse does not accept the "K" suffix for kelvins.
Constants and functions that return Celsius are listed under the Celsius type, not at the top level. go doc groups "constructors" with the type they return.
Add a symbol name to see one item:
$ go doc ./temp Parse
package temp // import "example.com/weather/temp"
func Parse(s string) (Celsius, error)
Parse parses s, a number optionally followed by "C" or "F". Values without a
suffix are treated as Celsius.
Parse returns an error if s is malformed or if the temperature is below
AbsoluteZero:
t, err := temp.Parse("451F")
if err != nil {
log.Fatal(err)
}
fmt.Println(t) // 232.8°C
Useful forms and flags:
| Command | Shows |
|---|---|
go doc fmt |
a standard library package |
go doc fmt.Println or go doc fmt Println |
one symbol |
go doc ./temp Celsius.Fahrenheit |
a method |
go doc -all ./temp |
every exported item with its full doc |
go doc -short ./temp |
one line per symbol |
go doc -src ./temp Parse |
the full source of the declaration |
go doc -u ./temp |
unexported items too |
go doc -http |
serves HTML documentation for the current package in a browser |
go doc -src is handy for quickly looking at a function body:
$ go doc -src ./temp Celsius.Fahrenheit
package temp // import "example.com/weather/temp"
// Fahrenheit returns c converted to degrees Fahrenheit.
func (c Celsius) Fahrenheit() float64 {
return float64(c)*9/5 + 32
}
See also Access documentation offline.
Documenting struct fields
Comments on struct fields are kept as written. Put a comment above a field or at the end of its line:
// Reading is a single measurement from a weather station.
type Reading struct {
// Station is the ICAO code of the station, such as "KSFO".
Station string
Value Celsius // measured temperature
At time.Time // when the measurement was taken, in UTC
raw string // original text, kept for debugging
}
$ go doc ./temp Reading
type Reading struct {
// Station is the ICAO code of the station, such as "KSFO".
Station string
Value Celsius // measured temperature
At time.Time // when the measurement was taken, in UTC
// Has unexported fields.
}
Reading is a single measurement from a weather station.
Unexported fields are hidden unless you pass -u. You can also ask for a single field with go doc ./temp Reading.Station.
What is not a doc comment
A comment is attached to a declaration only if nothing separates them. A blank line breaks the connection:
package orphan
// This comment is separated by a blank line,
// so it is not attached to Detached.
func Detached() {}
// Attached has a doc comment.
//
//go:noinline
func Attached() int { return 1 }
$ go doc -all ./orphan
FUNCTIONS
func Attached() int
Attached has a doc comment.
func Detached()
The //go:noinline line is a directive, not prose. Directives are written as // immediately followed by a word and a colon, with no space: //go:build, //go:generate, //go:embed, //go:noinline, //line. Documentation tools hide them. Keep the space in normal comments (// text) so that they're never mistaken for directives. See Build tags for //go:build.
Comments inside function bodies are never documentation. Use them to explain why code does something non-obvious, not to repeat what it does:
// Bad: says what the code already says.
i++ // increment i
// Good: explains a decision.
// Retry once: the first request after a cold start often times out.
resp, err = client.Do(req)
Doc comment syntax
Since Go 1.19, doc comments support a small, Markdown-like syntax. gofmt understands it and rewrites comments into the canonical form.
Paragraphs are separated by a blank // line. Lines in a paragraph are joined and re-wrapped when displayed, so don't rely on line breaks.
Headings are a line starting with # followed by text, with blank lines before and after. Use them to structure long package comments:
// # Precision
Doc links are names in square brackets. They become links in HTML docs and plain text in go doc:
| Form | Links to |
|---|---|
[Parse] |
Parse in the current package |
[Celsius.Fahrenheit] |
a method or field in the current package |
[math.Round] |
Round in an imported or standard package |
[encoding/json.Marshal] |
a symbol identified by its full import path |
[*bytes.Buffer] |
a pointer type (the * is allowed) |
URL links use a reference-style definition at the end of the comment. The definition line is [Text]: URL:
// The scales are described on [Wikipedia].
//
// [Wikipedia]: https://en.wikipedia.org/wiki/Temperature
A plain URL in the text, like https://go.dev, is also turned into a link.
Lists are indented lines that start with -, *, + or • (bulleted) or a number followed by . or ) (numbered):
// Supported suffixes:
// - C for Celsius
// - F for Fahrenheit
Code blocks are indented lines (gofmt uses a tab after //). They are shown in a monospace font and never re-wrapped:
// Example:
//
// t, err := temp.Parse("451F")
There's no syntax for bold, italics or inline code. To refer to a parameter, just use its name in the sentence: "Parse parses s...".
gofmt reformats doc comments
gofmt (and go fmt, see go fmt) normalizes doc comments: it adds the blank lines required around code blocks, uses a tab to indent code, and rewrites list markers. Given this file:
package fmtdemo
// Process handles a request.
// Steps:
// - validate input
// - run the job
// Example:
// Process(nil)
func Process(x any) {}
// Options:
// 1) fast
// 2) safe
func Options() {}
gofmt -d shows what it would change:
@@ -4,11 +4,13 @@
// Steps:
// - validate input
// - run the job
+//
// Example:
-// Process(nil)
+//
+// Process(nil)
func Process(x any) {}
// Options:
-// 1) fast
-// 2) safe
+// 1. fast
+// 2. safe
func Options() {}
This is a good way to check that a comment is parsed the way you meant. If gofmt turns your text into a code block, you indented something you didn't mean to.
Deprecated, BUG and TODO
Some paragraphs have special meaning.
Deprecated. A paragraph that starts with Deprecated: marks the item as deprecated:
// Kelvin returns c in kelvins.
//
// Deprecated: Use [Celsius.Kelvin] instead.
func Kelvin(c Celsius) float64 {
pkg.go.dev hides deprecated items by default, gopls shows uses of them crossed out, and linters such as staticcheck (check SA1019) warn when code calls them. Always say what to use instead.
BUG notes. A comment of the form // BUG(who): text at the top level of a file is collected into a "Bugs" section of the package docs. You can see it at the end of the go doc ./temp output above. It's rarely used outside the standard library.
TODO. // TODO: ... or // TODO(name): ... is a common convention for unfinished work, recognized by editors and by tools that grep for it. It has no special meaning in the docs, so keep TODOs inside function bodies or separate from doc comments.
Examples as documentation
Doc comments can include code blocks, but code in comments isn't compiled and can silently go stale. Example functions in _test.go files are better: go test runs them and checks their output, and pkg.go.dev shows them next to the function they document:
package temp_test
import (
"fmt"
"example.com/weather/temp"
)
func ExampleParse() {
t, err := temp.Parse("98.6F")
if err != nil {
panic(err)
}
fmt.Println(t)
// Output: 37.0°C
}
func ExampleCelsius_Fahrenheit() {
fmt.Println(temp.Boiling.Fahrenheit())
// Output: 212
}
$ go test -v ./temp
=== RUN ExampleParse
--- PASS: ExampleParse (0.00s)
=== RUN ExampleCelsius_Fahrenheit
--- PASS: ExampleCelsius_Fahrenheit (0.00s)
PASS
ok example.com/weather/temp 0.929s
The function name decides where the example appears: Example (the package), ExampleParse (function Parse), ExampleCelsius (type Celsius) and ExampleCelsius_Fahrenheit (method Celsius.Fahrenheit). See Example tests for more.
Rendering doc comments yourself
The standard library package go/doc/comment contains the parser and printers that gofmt, go doc and pkg.go.dev use. You can use it to render doc comments as HTML or Markdown, for example in a documentation generator:
package main
import (
"fmt"
"go/doc/comment"
)
const text = `Package temp converts between temperature scales.
# Conversions
Use [FromFahrenheit] to convert, or see [strconv.ParseFloat].
Supported suffixes:
- C for Celsius
- F for Fahrenheit
Example:
t, _ := temp.Parse("451F")
Details are on [Wikipedia].
[Wikipedia]: https://en.wikipedia.org/wiki/Temperature
`
func main() {
p := comment.Parser{
// Report which names exist in the current package,
// so [FromFahrenheit] becomes a link.
LookupSym: func(recv, name string) bool {
return recv == "" && name == "FromFahrenheit"
},
}
doc := p.Parse(text)
var pr comment.Printer
pr.DocLinkURL = func(link *comment.DocLink) string {
return link.DefaultURL("https://pkg.go.dev")
}
fmt.Println("=== Markdown ===")
fmt.Print(string(pr.Markdown(doc)))
fmt.Println("=== HTML ===")
fmt.Print(string(pr.HTML(doc)))
}
=== Markdown ===
Package temp converts between temperature scales.
### Conversions {#hdr-Conversions}
Use [FromFahrenheit](#FromFahrenheit) to convert, or see [strconv.ParseFloat](https://pkg.go.dev/strconv#ParseFloat). Supported suffixes:
- C for Celsius
- F for Fahrenheit
Example:
t, _ := temp.Parse("451F")
Details are on [Wikipedia](https://en.wikipedia.org/wiki/Temperature).
=== HTML ===
<p>Package temp converts between temperature scales.
<h3 id="hdr-Conversions">Conversions</h3>
<p>Use <a href="#FromFahrenheit">FromFahrenheit</a> to convert, or see <a href="https://pkg.go.dev/strconv#ParseFloat">strconv.ParseFloat</a>.
Supported suffixes:
<ul>
<li>C for Celsius
<li>F for Fahrenheit
</ul>
<p>Example:
<pre>t, _ := temp.Parse("451F")
</pre>
<p>Details are on <a href="https://en.wikipedia.org/wiki/Temperature">Wikipedia</a>.
Without LookupSym, the parser doesn't know that FromFahrenheit exists, and [FromFahrenheit] stays as literal text. Standard library packages such as strconv are recognized by default. To extract doc comments from Go source files, parse them with go/parser (using the parser.ParseComments mode) and pass the result to go/doc.
Publishing documentation
There's nothing to set up. When a module is public, pkg.go.dev fetches it through the module proxy and renders the doc comments, examples and README. To request a new version be indexed, visit https://pkg.go.dev/<module path>@<version> or fetch it through the proxy.
Checklist
- Every exported name has a doc comment that starts with that name.
- The package has exactly one package comment, starting with "Package name".
- Doc comments are full sentences that describe behavior, errors and edge cases (for example, what happens with
nilor an empty input). - Refer to other symbols with
[Name]so readers can click through. - Deprecated APIs have a
Deprecated:paragraph that names the replacement. - Usage examples are runnable
Examplefunctions rather than code in comments. - Run
gofmtand readgo docoutput to see what users will see.