Open this lesson in your favourite AI. It'll walk you through the why, explain the demo, and quiz you on the try-it list.
Go's documentation is generated from the source — every doc comment you read on pkg.go.dev was a comment in someone's .go file. The same docs are available offline via go doc. This is faster than tabbing to a browser and works on a plane. Knowing how to read package docs (especially the example functions, which are runnable tests) is the difference between guessing what bytes.Buffer does and knowing — and writing your own doc comments in the same style is how your code becomes navigable to teammates.
Go's documentation is generated from source comments — a comment immediately above a function, type, or package with no blank line becomes its doc string. go doc reads that documentation directly in your terminal: go doc json.Marshal prints the signature and doc comment; go doc -all encoding/json dumps the whole package. pkg.go.dev is the hosted version of the same data, plus dependency graphs, license info, and module version history. The discipline of writing doc comments as you code (not after) pays compounding returns: every go doc call you or a teammate makes is reading your code as prose.
go doc strings and read the package summary. Then go doc strings.Builder for one type. Note how short and precise these are.pkg.go.dev/strings in a browser. Compare to go doc — same content, different presentation.go doc ./... to see your package's generated docs.pkg.go.dev/strings. These are real runnable functions named ExampleX in test files — they're tested by go test and rendered into the docs.Use these three in order. Each builds on the one before.
In one paragraph, explain the convention `// Foo does X.` for doc comments — why does the comment have to start with the function name?
How does pkg.go.dev know about your repo? Walk me through the Go module proxy, the fetch flow, and what happens when I tag a new release.
I'm writing a library and want my docs to be world-class. What does idiomatic doc style look like — examples, doc comments on exported types, package-level doc, runnable Example functions? Show me the structure.
# package summary:
$ go doc fmt
package fmt // import "fmt"
Package fmt implements formatted I/O with functions analogous to C's printf
and scanf...
# specific symbol:
$ go doc fmt.Errorf
func Errorf(format string, a ...any) error
Errorf formats according to a format specifier and returns the string
as a value that satisfies error. If the format specifier includes a %w
verb with an error operand, the returned error will implement an Unwrap
method...
# show source:
$ go doc -src fmt.Errorf
# in your own code, doc comments are just comments above the symbol:
// Sum returns the total of the inputs. It panics on overflow.
func Sum(xs ...int) int { ... }go run main.go