Go by Example: Comments
Comments in Go serve two purposes: explaining code to developers and generating documentation via `godoc`. This example shows how to write effective package, function, and line comments, as well as how to use directives.
Code
// Package main demonstrates best practices for Go comments.
//
// The package comment should introduce the package and provide
// a high-level overview. It appears first in the godoc output.
package main
import "fmt"
// User represents a system user.
//
// Doc comments for types should start with the type name.
type User struct {
ID int
Name string
}
// NewUser creates a user with the given ID and name.
//
// Doc comments for functions should be complete sentences
// starting with the function name. This allows godoc to
// extract them for summaries.
func NewUser(id int, name string) *User {
return &User{ID: id, Name: name}
}
// UpdateName changes the user's display name.
//
// Deprecated: Use UpdateProfile instead. This method will be
// removed in v2.0.
func (u *User) UpdateName(newName string) {
u.Name = newName
}
func main() {
// Line comments explain the "why", not the "what".
// Bad: i++ // Increment i
// Good: i++ // Skip the CSV header row
u := NewUser(1, "Alice")
// TODO(jdoe): Refactor this to use the new database API.
// TODOs often include a username and context.
fmt.Println("User:", u.Name)
// Directives are special comments for tools.
// They must start at the beginning of the line (no spaces).
//go:noinline
_ = func() { fmt.Println("I won't be inlined") }
}
Explanation
Comments in Go are treated as first-class citizens, primarily because the godoc tool parses them to generate documentation. To write idiomatic Go comments, you should focus on the "Why" rather than the "What". The code itself usually explains what it's doing; the comment should explain the context, design decisions, or complex algorithms.
For documentation, every exported (capitalized) name should have a doc comment. A doc comment must appear immediately before the declaration, with no empty lines. By convention, it should be a complete sentence starting with the name of the item being documented (e.g., // Fprint formats...). This consistency allows tools to easily extract one-line summaries.
Go also uses comments for tool directives. These are special comments that start with //go: (no space) and instruct the compiler or other tools to do something specific, like //go:generate to run code generators or //go:embed to embed files.
- Doc Comments: Start with the entity name (e.g.,
// User represents...). - Package Comments: Place immediately before
packageclause. - Directives: No space after slashes (e.g.,
//go:generate). - Deprecation: Use
// Deprecated: reasonto mark old APIs.

