Skip to content
Tutorials Center
My learning

Topics

Lesson 4 of 147 ยท Getting Started

Comments and Documentation

Learn Go comments - line and block comments, doc comments that become documentation, package comments, Deprecated markers, TODO conventions and special directives.

Comments explain what code cannot say by itself: why a decision was made, what a function promises, what to watch out for. In Go, comments have a second job as well. The comment directly above a declaration is its documentation, and tools such as go doc, pkg.go.dev and your editor's hover tips show it to everyone who uses your code.

This lesson covers both comment styles, how to write doc comments the Go way, the conventions for package comments, deprecation and TODO notes, and the special comments that talk to the compiler.

Line and block comments

Go has two kinds of comment, the same as C:

  • // starts a line comment that runs to the end of the line.
  • /* ... */ is a block comment that can span several lines.
Go Both kinds of comment

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

In practice Go programmers use // almost everywhere, including for long explanations (just start each line with //). Block comments are mostly kept for two cases: temporarily disabling a chunk of code, and the occasional inline note like /* ... */ in the middle of a line.

Comments have one more effect: they take the place of whitespace. A comment containing a newline counts as a newline for automatic semicolon insertion (see Go Syntax), and a comment without one counts as a space.

Block comments do not nest. The first */ ends the comment, no matter how many /* came before it. Commenting out code that already contains a block comment is therefore a classic trap. Prefer // on every line, which editors do for you with one shortcut.

Go Block comments do not nest (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The comment ends at the first */, so still outer? is read as code and the compiler prints several errors, starting with ./main.go:8:11: syntax error: unexpected name outer at end of statement. Follow-up errors after the first one are noise, so remember the cause, not the messages.

Doc comments

A doc comment is a comment that sits immediately above a package, constant, variable, type, function or method declaration, with no blank line in between. The tools treat it as the declaration's documentation.

The rules are few and strict, and following them makes your code read like the standard library:

  1. Write complete sentences.
  2. Start with the name of the thing you describe: // Add returns the sum of a and b.
  3. Document exported names. Unexported ones may have comments too, but nothing requires it.
  4. Say what the function does for a caller, not how it does it.
Go Doc comments on a function and a type

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

On your machine, go doc would print these comments next to the signatures:

TEXT
$ go doc Greeter
type Greeter struct {
	// Has unexported fields.
}
    A Greeter says hello to one person.

    The zero value is not usable; create one with NewGreeter.

func NewGreeter(name string) (*Greeter, error)
func (g *Greeter) Greet() string

Formatting inside doc comments

Doc comments are plain text with a small amount of structure, understood by gofmt and the documentation tools:

  • A blank // line separates paragraphs.
  • A line indented by a tab or spaces after // is a code block.
  • A line starting with - or * (or a number and a dot) is a list item.
  • A line starting with # and a title, standing alone, is a heading (Go 1.19 and later).
  • [Name] links to another identifier in the same package, and [pkg.Name] links to one in another package, such as [strings.Builder].

The standard library even ships the parser that does this. The next program renders a doc comment into plain text, the same engine go doc uses (the go/doc/comment package):

Go Rendering a doc comment with go/doc/comment

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The printer shows the heading, the paragraph, the list and the indented code block in the layout go doc uses in a terminal.

Package comments

The documentation for a whole package is a doc comment placed right above the package clause, starting with Package and the package's name:

Go
// Package slugify turns titles into URL-friendly slugs.
//
// It lowercases text, removes punctuation and joins words with hyphens:
//
//	slugify.Make("Hello, Go World!") // "hello-go-world"
package slugify

When a package has several files, only one of them needs the package comment (people often put it in a file called doc.go). For a package main program, the comment usually starts with the command's name instead, for example // Command wordcount counts words in files.

Deprecated, TODO and friends

Marking something deprecated

To tell users to stop using an exported name, add a paragraph to its doc comment that starts with Deprecated:. Editors and linters then strike through the name and show your message:

Go
// ParseLegacy parses the version 1 format.
//
// Deprecated: Use Parse instead, which also understands version 2.
func ParseLegacy(s string) (Config, error) { /* ... */ }

The word must be capitalized exactly like that, followed by a colon, at the beginning of a paragraph.

TODO, FIXME and BUG

Go does not enforce any marker, but the usual convention is // TODO(name): what is left to do, where the name says who to ask, not who must do it. A comment starting with BUG(who): is even picked up by the documentation tools and shown in a "Bugs" section.

Go
// TODO(mira): handle time zones other than UTC.

Keep these notes honest and short, and remove them when the work is done. If a TODO never gets done, an issue tracker is the better home for it.

Directive comments

A few comments are instructions to tools. They look like //go:something with no space after the slashes, and gofmt places them at the end of a doc comment:

Go
//go:build linux && amd64

package platform
  • //go:build selects which platforms or conditions a file is compiled for (a build constraint; it must come before the package clause).
  • //go:embed copies files into a variable at build time.
  • //go:generate lists a command that go generate runs.
  • //go:noinline and similar control the compiler and are used in performance work.

These are advanced tools, so just remember the rule: a comment starting with //go: is not an ordinary comment, and a space after // turns it back into one.

Writing good comments

  • Explain why, not what. i++ // add one to i is noise. // retry once: the server closes idle connections after 30s is useful.
  • Keep comments true. An outdated comment is worse than none, so update it when the code changes.
  • Prefer clear names. If a comment is needed to explain what a variable is, rename the variable first.
  • Document behavior callers rely on: what happens with nil or empty input, whether the function is safe for concurrent use, what errors it returns.

You will see these habits throughout the standard library, and Documentation later in the course shows how to publish example functions that appear in the generated docs and are tested automatically.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which comment is a correct doc comment for an exported function Sum?

    A doc comment is a full sentence that starts with the name of the thing it documents.
  2. 2. What happens to nested block comments such as /* a /* b */ c */ ?

    Block comments do not nest. The first */ closes the comment.
  3. 3. How do you mark an exported function as deprecated?

    A paragraph beginning with 'Deprecated:' is recognized by tools such as editors and linters.
  4. 4. Where does the package comment go?

    The doc comment immediately above 'package x' documents the package. It starts with 'Package x'.
  5. 5. What is special about a comment like //go:build linux ?

    Comments of the form //go:... (no space) are instructions to the toolchain. A build constraint decides which files are compiled.

Summary

  • Use // for almost everything; /* */ exists but does not nest.
  • A comment directly above a declaration is its doc comment. Write full sentences that start with the name.
  • Package comments sit above the package clause and start with Package name.
  • Deprecated: paragraphs, TODO(name): notes and //go: directives are conventions understood by people and tools.
  • Doc comments support paragraphs, lists, headings, code blocks and [Name] links, and gofmt keeps them tidy.
  • Explain why, keep comments true, and prefer clear names over explanatory comments.

Next: Printing with fmt goes deep into fmt and its formatting verbs.