These are the notes for Go episode 29. In episode 27 the chai shop's code was split into packages, and in episode 28 it became a proper module with dependencies. Now it grows into a real project: more than one program, a new teammate who has to understand the code, and bugs that compile without a single error. In this episode you invent, one problem at a time, what real Go teams use every day. You will lay out several programs with a cmd/ folder and keep shared code private in internal/, and hear both sides of the pkg/ debate. You will write doc comments and a package comment, read them with go doc, link names with [Name], and see where they end up: pkg.go.dev. You will write example functions (ExampleTotal with // Output:) that go test checks, so documentation can never quietly go stale. You will meet the two style guides, Effective Go and Go Code Review Comments, format code with gofmt -l, -d and -w, watch a Printf bug compile and run wrong, and catch it with go vet. Finally you meet the tools teams install on top: staticcheck, golangci-lint, gofumpt and goimports. Every command was run for real with Go 1.24.7 (linux/amd64) in a module called example.com/shop. staticcheck, golangci-lint, gofumpt and goimports were not installed, so they are described from their documentation only, with no invented output.
The problem: the shop needs two programs
Raju's chai shop has one program: the counter program, which bills customers. Now Raju also wants a daily report program, so he can see at night how many samosas were sold. The obvious idea: put report.go next to main.go, each with its own func main.
shop/
├── go.mod module example.com/shop
├── main.go package main, func main (the counter)
└── report.go package main, func main (the daily report)
Both files are the same except for the message (main.go prints counter, report.go prints report):
package main
import "fmt"
func main() {
fmt.Println("counter")
}
$ go run .
# example.com/shop
./report.go:5:6: main redeclared in this block
./main.go:5:6: other declaration of main
- Redeclared means the same name was declared twice in one place (episode 27).
- Why it failed: one folder is one package (episode 27). Both files say
package main, so they are compiled together as one program, and a program can have only onemainfunction. go run main.go(naming only one file) does run the counter and printscounter, but that is a trick, not a layout: every tool that works on the folder (go build,go vet,go test) still sees twomainfunctions.
What we need: one folder per program. Like a shop building with separate counters.
cmd/ and internal/
Think of a shop building:
| In a shop building | In a Go module | Meaning |
|---|---|---|
| Separate counters: a tea counter, a snacks counter | cmd/<name>/main.go |
one folder per program |
| The back kitchen: shared by every counter, staff only | internal/ |
shared code that no outsider may use |
| The shop front: what visitors may use | the module root or plain folders | packages that other people may import |
cmd/is short for commands. A command is a runnable program (apackage main). Each program gets its own folder undercmd/:cmd/shop/main.gois the counter,cmd/report/main.gois the daily report. The folder name becomes the program's name when you build it.internal/is the special folder from episode 27: a package whose import path containsinternalcan be imported only by code in the folder that contains thatinternalfolder. A top-levelinternal/sits at the module root (the folder that holdsgo.mod), so every package in this module may import it, and no other module can.- Code that other projects should import goes at the module root or in plain folders (not under
internal/).
The official guide "Organizing a Go module" on go.dev describes exactly these layouts:
| Layout from the guide | What it looks like | When |
|---|---|---|
| Basic package | .go files at the module root, one importable package |
a small library |
| Basic command | main.go at the module root |
one small program |
| Multiple commands | cmd/ with one folder per program |
several programs in one repository |
Packages in internal/ |
shared code under internal/ |
code the module's own programs share |
| Server project | logic kept in internal/, programs in cmd/ |
a server that nobody imports as a library |
The guide's advice: keep packages in internal as much as possible. Code in internal/ can be changed freely, because no other module can depend on it. And, important for the next section, the guide never mentions pkg/.
The fixed shop
shop/
├── go.mod module example.com/shop
├── cmd/
│ ├── shop/main.go package main: the counter
│ └── report/main.go package main: daily report
└── internal/
└── billing/
├── billing.go package billing
└── example_test.go
internal/billing has Price and Total (shown in the next section). cmd/shop/main.go calls billing.Total("chai", "chai") and cmd/report/main.go calls 12*billing.Price("samosa"); their full code is in the mini project solution.
$ go run ./cmd/shop
counter: chai x2 = 20
$ go run ./cmd/report
report: 12 samosas = 180
go run ./cmd/shopbuilds and runs the package in the foldercmd/shop. The./at the front says "a folder, relative to here", not an import path.- Both programs import
example.com/shop/internal/billing: the import path is the module path plus the folder (episode 27).
The ./... pattern
... in a package pattern means "this folder and every folder below it". So ./... is the whole module, and ./cmd/... is every program.
$ go list ./...
example.com/shop/cmd/report
example.com/shop/cmd/shop
example.com/shop/cmd/stock
example.com/shop/internal/billing
(cmd/stock is a third program that arrives later in this episode.) Build every program at once:
$ go build -o bin/ ./cmd/...
$ ls bin
report
shop
stock
-o bin/means "put the built programs in the folderbin/". The trailing/matters: with several packages,-omust name a folder. Each program is named after its folder.
internal/ really is private
A second module, example.com/other, has a main.go that imports "example.com/shop/internal/billing" and prints billing.Price("chai") (it finds the shop code on disk through a replace line in its go.mod, from episode 28):
$ go run .
package example.com/other
main.go:6:2: use of internal package example.com/shop/internal/billing not allowed
That is the back kitchen door: staff only.
The pkg/ debate
On GitHub you will see many projects with a pkg/ folder, holding the packages that others may import: example.com/shop/pkg/billing.
For pkg/ |
Against pkg/ |
|---|---|
| a clear sign: "everything in here is meant for importing" | the go.dev guide never uses it: public packages go at the root or in plain folders |
| keeps the root folder tidy in big repositories | it adds an extra word to every import path (.../pkg/billing) |
| many well-known projects use it, so readers know it | it doesn't make anything safer: only internal/ is enforced by the Go tool |
What both sides agree on: start simple.
- A small program: one folder with
main.go(the "basic command"). - Two programs: add
cmd/. - Shared code: add
internal/, and keep packages there as much as possible. pkg/is a team choice, never a requirement.
Doc comments and go doc
A new teammate joins and asks: what does Price return for "masala", which isn't on the menu? A panic? Minus one? Zero? With no comments, they have to read the code:
package billing
var prices = map[string]int{"chai": 10, "samosa": 15}
func Price(item string) int {
return prices[item]
}
func Total(items ...string) int {
sum := 0
for _, it := range items {
sum += Price(it)
}
return sum
}
go doc prints the documentation of a package or a name in the terminal. Run on the uncommented package, it shows only the signatures (a function's name, parameters and results):
$ go doc ./internal/billing
package billing // import "example.com/shop/internal/billing"
func Price(item string) int
func Total(items ...string) int
Nothing about what they mean. In a kitchen every jar has a label, so nobody has to open it. Go's labels:
| In the kitchen | In Go | Where |
|---|---|---|
| Label on the jar: "Garam masala, 100 g" | doc comment: // Price returns ... |
directly before the declaration |
| Label on the shelf: "Spices" | package comment: // Package billing ... |
before the package line, once per package |
From the official guide Go Doc Comments (go.dev/doc/comment):
- A doc comment is a comment written directly before a top-level
package,const,func,typeorvardeclaration, with no blank line in between. ("Top-level" means outside any function.) - "Every exported (capitalized) name should have a doc comment." (An exported name starts with a capital letter and can be used by other packages; episode 27.)
- The package comment goes before the package clause and begins with "Package" and the package's name:
// Package billing .... Only one file in the package needs to carry it. - A function's comment starts with a full sentence that names the symbol: "Price returns ...". It says what the function returns or does, including the surprising cases.
- A function that returns a bool is described with "reports whether":
// IsOpen reports whether the shop is open. - Doc comments are read by
go doc, by pkg.go.dev, and by gopls (the Go language server that powers editors such as VS Code, showing docs when you hover over a name).
internal/billing/billing.go with doc comments:
// Package billing works out prices and bills for the chai shop.
package billing
var prices = map[string]int{"chai": 10, "samosa": 15}
// Price returns the price of one item in rupees.
// It returns 0 if the item is not on the menu.
func Price(item string) int {
return prices[item]
}
// Total returns the bill for all the items, in rupees.
// Unknown items cost nothing; see [Price].
func Total(items ...string) int {
sum := 0
for _, it := range items {
sum += Price(it)
}
return sum
}
[Price]is a doc link: a name in square brackets. Websites such as pkg.go.dev turn it into a clickable link toPrice's documentation. It can also name another package's symbol, like[strings.Fields]. In the terminal,go docsimply prints the name without brackets.
go doc, again
$ go doc ./internal/billing
package billing // import "example.com/shop/internal/billing"
Package billing works out prices and bills for the chai shop.
func Price(item string) int
func Total(items ...string) int
$ go doc ./internal/billing.Price
package billing // import "example.com/shop/internal/billing"
func Price(item string) int
Price returns the price of one item in rupees. It returns 0 if the item is
not on the menu.
The teammate's question is answered: 0.
$ go doc ./internal/billing.Total
package billing // import "example.com/shop/internal/billing"
func Total(items ...string) int
Total returns the bill for all the items, in rupees. Unknown items cost
nothing; see Price.
Notice see Price: the brackets of the doc link are gone in the terminal.
go doc on the standard library
It works for the standard library too, offline:
$ go doc strings.Fields
package strings // import "strings"
func Fields(s string) []string
Fields splits the string s around each instance of one or more consecutive
white space characters, as defined by unicode.IsSpace, returning a slice of
substrings of s or an empty slice if s contains only white space.
More go doc flags
| Command | What it shows |
|---|---|
go doc ./internal/billing |
package comment + a one-line list of exported names |
go doc ./internal/billing.Price |
one name with its doc comment |
go doc -all ./internal/billing |
the whole package: every exported name with its comment |
go doc -src ./internal/billing.Price |
the source code of that name, comment included |
go doc -u ./internal/billing |
also unexported (lowercase) names |
go doc -short ./internal/billing |
one line per name, no package header |
$ go doc -all ./internal/billing
package billing // import "example.com/shop/internal/billing"
Package billing works out prices and bills for the chai shop.
FUNCTIONS
func Price(item string) int
Price returns the price of one item in rupees. It returns 0 if the item is
not on the menu.
func Total(items ...string) int
Total returns the bill for all the items, in rupees. Unknown items cost
nothing; see Price.
$ go doc -src ./internal/billing.Price
package billing // import "example.com/shop/internal/billing"
// Price returns the price of one item in rupees.
// It returns 0 if the item is not on the menu.
func Price(item string) int {
return prices[item]
}
$ go doc -u ./internal/billing
package billing // import "example.com/shop/internal/billing"
Package billing works out prices and bills for the chai shop.
var prices = map[string]int{ ... }
func Price(item string) int
func Total(items ...string) int
go doc -short ./internal/billing prints just the two lines func Price(item string) int and func Total(items ...string) int.
A blank line breaks the label
If a blank line sits between the comment and the function, the comment is no longer a doc comment:
// Price returns the price of one item in rupees.
// It returns 0 if the item is not on the menu.
func Price(item string) int {
return prices[item]
}
$ go doc ./internal/billing.Price
package billing // import "example.com/shop/internal/billing"
func Price(item string) int
The label fell off the jar. No error, no warning: just no documentation.
Examples that are tested
Comments have one weakness: when the code changes, an old comment can quietly become wrong, or stale. Go has documentation that is checked: example functions.
internal/billing/example_test.go:
package billing_test
import (
"fmt"
"example.com/shop/internal/billing"
)
func ExampleTotal() {
fmt.Println(billing.Total("chai", "chai", "samosa"))
// Output: 35
}
func ExamplePrice() {
fmt.Println(billing.Price("masala"))
// Output: 0
}
- The file name ends in
_test.go: such files are compiled only bygo test, never into the programs. - An example function is named
Exampleplus the name it documents:ExampleTotaldocumentsTotal. It takes no parameters and returns nothing. - It prints with
fmt.Println. The comment// Output:at the end gives the exact expected output.go testruns the example and compares what it printed with that comment. package billing_testis an external test package: a separate package, in the same folder, that may usebillingonly from the outside, through its exported names and an import, like a real user would. Go allows exactly this one extra package name (the package name plus_test) in a folder. Testing gets a full episode later in the course (episode 40).
$ go test -v ./internal/billing
=== RUN ExampleTotal
--- PASS: ExampleTotal (0.00s)
=== RUN ExamplePrice
--- PASS: ExamplePrice (0.00s)
PASS
ok example.com/shop/internal/billing 0.004s
-vmeans verbose: show every test and example by name, not just the finalok.
Now someone changes the comment to // Output: 30, but the code still prints 35:
$ go test ./internal/billing
--- FAIL: ExampleTotal (0.00s)
got:
35
want:
30
FAIL
FAIL example.com/shop/internal/billing 0.001s
FAIL
Wrong documentation is now a failing test. An example can never quietly go stale. And pkg.go.dev shows examples right next to the function's documentation.
Example naming
| Name | Documents | Shown on the docs page under |
|---|---|---|
Example() |
the whole package | the package |
ExampleTotal() |
the function Total |
Total |
ExampleBill() |
the type Bill |
Bill |
ExampleBill_Add() |
the method Add of type Bill (ExampleT_Method) |
Bill.Add |
ExampleTotal_unknown() |
a second example of Total, called "unknown" (Example_suffix style: the suffix starts with a lower-case letter) |
Total |
An example without an output comment is compiled (so it must still build) but not run.
// Unordered output: is used when the lines may come out in any order, as when you range over a map (map order is random in Go). The lines must match, in any order.
To try these, the billing package got a small type and a function (internal/billing/bill.go):
package billing
// Bill is one customer's order at the counter.
type Bill struct {
items []string
}
// Add puts one more item on the bill.
func (b *Bill) Add(item string) {
b.items = append(b.items, item)
}
// Sum returns the total of the bill in rupees.
func (b *Bill) Sum() int {
return Total(b.items...)
}
// Menu returns the price of every item on the menu.
func Menu() map[string]int {
m := make(map[string]int)
for k, v := range prices {
m[k] = v
}
return m
}
internal/billing/more_example_test.go:
package billing_test
import (
"fmt"
"example.com/shop/internal/billing"
)
// A whole-package example: a customer orders two chais.
func Example() {
var b billing.Bill
b.Add("chai")
b.Add("chai")
fmt.Println("bill:", b.Sum())
// Output: bill: 20
}
func ExampleTotal_unknown() {
fmt.Println(billing.Total("chai", "masala"))
// Output: 10
}
func ExampleBill_Add() {
var b billing.Bill
b.Add("samosa")
fmt.Println(b.Sum())
// Output: 15
}
func ExampleMenu() {
for item, price := range billing.Menu() {
fmt.Println(item, price)
}
// Unordered output:
// samosa 15
// chai 10
}
func ExampleBill_Sum() {
var b billing.Bill
b.Add("chai")
fmt.Println(b.Sum())
}
$ go test -v ./internal/billing
=== RUN ExampleTotal
--- PASS: ExampleTotal (0.00s)
=== RUN ExamplePrice
--- PASS: ExamplePrice (0.00s)
=== RUN Example
--- PASS: Example (0.00s)
=== RUN ExampleTotal_unknown
--- PASS: ExampleTotal_unknown (0.00s)
=== RUN ExampleBill_Add
--- PASS: ExampleBill_Add (0.00s)
=== RUN ExampleMenu
--- PASS: ExampleMenu (0.00s)
PASS
ok example.com/shop/internal/billing 0.002s
ExampleBill_Sumis missing from the list: it has no output comment, so it was only compiled.ExampleMenupassed even though the map may printchaifirst, thanks to// Unordered output:.
With a plain // Output: instead, the same map example fails whenever the order differs. A real run (-count=10 runs it ten times):
$ go test -run ExampleMenu -count=10 ./internal/billing
--- FAIL: ExampleMenu (0.00s)
got:
chai 10
samosa 15
want:
samosa 15
chai 10
FAIL
FAIL example.com/shop/internal/billing 0.008s
FAIL
Badly named examples
A typo in an example's name is caught too. This file:
func ExampleTotl() {
fmt.Println(billing.Total("chai"))
// Output: 10
}
func ExampleTotal_Masala() {
fmt.Println(billing.Total("masala"))
// Output: 0
}
$ go test ./internal/billing
# example.com/shop/internal/billing_test
# [example.com/shop/internal/billing_test]
internal/billing/bad_example_test.go:9:1: ExampleTotl refers to unknown identifier: Totl
internal/billing/bad_example_test.go:14:1: ExampleTotal_Masala refers to unknown field or method: Total.Masala
FAIL example.com/shop/internal/billing [build failed]
FAIL
Totldoesn't exist. And_Masalastarts with a capital letter, so Go reads it as a method calledMasalaonTotal(theExampleT_Methodform). A suffix must start with a lower-case letter:ExampleTotal_masala.- This check comes from go vet, which
go testruns automatically (more on that below).
pkg.go.dev
Where do doc comments end up? pkg.go.dev: "a website for discovering and evaluating Go packages and modules". Search any public module, like github.com/google/uuid from episode 28, and you see its package comment, doc comments, examples, versions, and which other packages import it. The same goes for the whole standard library. When your module is public, its documentation appears there too, built from the same doc comments that go doc reads. (A package under internal/ can't be imported by others, so it matters less there; the comments still help your own team in go doc and the editor.)
Style guides: Effective Go and Go Code Review Comments
Go's team wrote down how Go is meant to be written.
- Effective Go (on go.dev) explains how to write clear, idiomatic Go. Idiomatic means "the way experienced Go programmers naturally write it", like speaking a language the way native speakers do, not word-by-word translated from another language.
- Go Code Review Comments is "a supplement to Effective Go": the comments reviewers make again and again in code reviews (when a teammate reads your change before it is accepted). It calls itself "a laundry list of common mistakes, not a style guide".
Some of its topics:
| Topic | What it says, in short |
|---|---|
| Gofmt | run gofmt on your code; no arguing about formatting |
| Comment Sentences | comments are full sentences that start with the name being described |
| Doc Comments | every exported name should have a doc comment |
| Error Strings | not capitalised, no punctuation at the end (episode 24) |
| Receiver Names | short (one or two letters, like b for *Bill), never self or this |
| Package Names | short, lower case, no stutter (episode 27) |
| Variable Names | short names for short scopes (i, b), longer for wider ones |
| Don't Panic | use error values for normal errors, not panic |
Why error strings are lower case with no full stop: they usually get wrapped inside other messages. A real run:
package main
import (
"errors"
"fmt"
)
func find(item string) error {
return errors.New("Item not found.")
}
func main() {
err := find("masala")
fmt.Println(fmt.Errorf("billing masala: %w", err))
}
billing masala: Item not found.
After changing it to errors.New("item not found"):
billing masala: item not found
The capital letter and full stop in the middle of a sentence looked wrong.
gofmt: one format for everyone
A third program arrives, cmd/stock/main.go, written in a hurry:
package main
import "fmt"
func main() {
item:="chai"
cups := 12
fmt.Printf("%s: %d cups left\n",item,cups)
}
Random spaces, no spaces around :=, after the commas. In a team, everyone's taste differs, and reviews turn into arguments about spaces. gofmt (episode 1) ends that: it formats Go code in the standard style.
-l (list) prints the names of files whose formatting differs:
$ gofmt -l .
cmd/stock/main.go
-d (diff) shows the change without making it. A diff is a list of differences between two versions of a file: lines starting with - would be removed, lines starting with + would be added, lines with a space are unchanged context. @@ -3,7 +3,7 @@ means "7 lines starting at line 3, in both versions".
$ gofmt -d cmd/stock/main.go
diff cmd/stock/main.go.orig cmd/stock/main.go
--- cmd/stock/main.go.orig
+++ cmd/stock/main.go
@@ -3,7 +3,7 @@
import "fmt"
func main() {
- item:="chai"
- cups := 12
- fmt.Printf("%s: %d cups left\n",item,cups)
+ item := "chai"
+ cups := 12
+ fmt.Printf("%s: %d cups left\n", item, cups)
}
Tabs for indentation, one space around operators and after commas.
-w (write) writes the fix into the file. Then -l prints nothing:
$ gofmt -w cmd/stock/main.go && gofmt -l .
$
package main
import "fmt"
func main() {
item := "chai"
cups := 12
fmt.Printf("%s: %d cups left\n", item, cups)
}
$ go run ./cmd/stock
chai: 12 cups left
| Flag | Does | Changes files? |
|---|---|---|
gofmt -l . |
lists unformatted files | no |
gofmt -d file.go |
prints the diff | no |
gofmt -w file.go |
rewrites the file | yes |
gofmt -l -w . |
rewrites every file below . and lists the ones it changed |
yes |
Without -w, gofmt never touches your files. Most editors run gofmt every time you save. go fmt ./... (with a space) is the go command's shortcut that runs gofmt -l -w on packages.
go vet: compiles, but suspicious
Formatting is solved. But a program can be perfectly formatted, compile, and still be wrong. Someone "fixed" the stock program and swapped the verbs (the % codes in a format string that say how to print each value): %d (a whole number) for the string, %s (a string) for the number.
package main
import "fmt"
func main() {
item := "chai"
cups := 12
fmt.Printf("%d: %s cups left\n", item, cups)
}
$ go run ./cmd/stock
%!d(string=chai): %!s(int=12) cups left
It compiled and ran. %!d(string=chai) is fmt's way of saying "verb %d got a string, chai". The bug reached the output. Why didn't the compiler stop it? To the compiler, Printf just takes a string and any values (format string, a ...any). It doesn't read inside the format string.
This is what go vet is for. go vet is a static analysis tool built into Go. Static analysis means checking code without running it, just by reading it, like re-adding a bill on paper before giving it to the customer.
$ go vet ./...
# example.com/shop/cmd/stock
# [example.com/shop/cmd/stock]
cmd/stock/main.go:8:2: fmt.Printf format %d has arg item of wrong type string
Caught before any customer saw it. go vet's own help describes it: it "examines Go source code and reports suspicious constructs, such as Printf calls whose arguments do not align with the format string". It uses heuristics (good guesses that are usually right), so it looks for code that compiles but is almost certainly a mistake, not for style.
More things go vet catches
A scratch module example.com/vetzoo, with several classic mistakes, all of which compile:
package main
import (
"fmt"
"sync"
)
type Counter struct {
mu sync.Mutex
cups int
}
func report(c Counter) {
fmt.Println("cups:", c.cups)
}
func price(item string) int {
return 10
fmt.Println("never runs")
return 0
}
func main() {
var c Counter
c.cups = 12
report(c)
cups := 12
cups = cups
fmt.Println("cups: %d", cups)
fmt.Printf("%s costs %d\n", "chai")
fmt.Println(price("chai"))
}
$ go run .
cups: 12
cups: %d 12
chai costs %!d(MISSING)
10
$ go vet ./...
# example.com/vetzoo
# [example.com/vetzoo]
./main.go:29:2: self-assignment of cups to cups
./main.go:13:15: report passes lock by value: example.com/vetzoo.Counter contains sync.Mutex
./main.go:26:9: call of report copies lock value: example.com/vetzoo.Counter contains sync.Mutex
./main.go:30:2: fmt.Println call has possible Printf formatting directive %d
./main.go:31:2: fmt.Printf format %d reads arg #2, but call has 1 arg
./main.go:19:2: unreachable code
| Message | The mistake |
|---|---|
self-assignment of cups to cups |
cups = cups does nothing |
passes lock by value / copies lock value |
a sync.Mutex (a lock, used to let only one goroutine touch data at a time; covered with concurrency later in the course) was copied; a copied lock doesn't protect the original |
possible Printf formatting directive %d |
Println doesn't understand %d; you meant Printf |
reads arg #2, but call has 1 arg |
two verbs, one value: prints %!d(MISSING) |
unreachable code |
code after return can never run |
Each check is a separate analyzer. go tool vet help lists them all; in Go 1.24.7 they include appends, assign, atomic, bools, buildtag, copylocks, directive, errorsas, ifaceassert, loopclosure, lostcancel, nilfunc, printf, stringintconv, structtag, tests, unreachable, unusedresult and more. You can run just one with its flag: go vet -copylocks ./... printed only the two lock lines above.
go test runs some vet checks for you
go help test says: go test runs a high-confidence subset of vet checks: atomic, bool, buildtags, directive, errorsas, ifaceassert, nilfunc, printf, stringintconv and tests. If one fails, the test fails before running. With a small test file added to vetzoo:
$ go test .
# example.com/vetzoo
# [example.com/vetzoo]
./main.go:30:2: fmt.Println call has possible Printf formatting directive %d
./main.go:31:2: fmt.Printf format %d reads arg #2, but call has 1 arg
FAIL example.com/vetzoo [build failed]
FAIL
Only the two printf problems: the lock copy, self-assignment and unreachable code are not in the subset. So go test is not a replacement for go vet ./.... -vet=off turns the checks off:
$ go test -vet=off .
ok example.com/vetzoo 0.003s
Even a package with no test files gets the check: go test ./cmd/stock on the Printf bug failed with the same fmt.Printf format %d has arg item of wrong type string line and FAIL example.com/shop/cmd/stock [build failed].
Rule of thumb: run go vet ./... before every commit (a commit is a saved snapshot of your changes in Git).
Linters: the senior cashier
Think of a bill going out of the shop:
| At the shop | In Go | Checks |
|---|---|---|
| Neat handwriting that everyone can read | gofmt / gofumpt (formatters) | how the code looks |
| Someone re-adds the total to catch obvious slips | go vet (built in) | clear mistakes |
| A senior cashier who spots subtle problems | staticcheck (a linter) | bugs, dead code, style |
A linter is a tool that reads code and reports bugs, dead code (code that is never used) and style problems. go vet is a small, careful linter that ships with Go. The tools below are installed separately, with go install, or pinned in go.mod with the tool directive from episode 28. None of them were run for these notes, so no output is shown.
staticcheck
- Describes itself as "go vet on steroids": many more checks.
- Run it on every package:
staticcheck ./... - Its checks are grouped by number:
| Group | Finds |
|---|---|
| SA1 | misuses of the standard library |
| SA2 | concurrency issues |
| SA3 | testing issues |
| SA4 | code that isn't really doing anything |
| SA5 | correctness issues |
| SA6 | performance issues |
| SA9 | dubious constructs |
golangci-lint
- Calls itself a "Smart, fast linters runner": one command runs many linters at once (staticcheck among them), configured in one file in your repository.
golangci-lint runlints the code.golangci-lint fmtruns formatters;golangci-lint fmt -dshows a diff instead of changing files.golangci-lint run --fixapplies the fixes that linters suggest.- Version 2 was released on 23 March 2025, with a new
formatterssection in the config file. Its--defaultoption picks the starting set of linters:standard,all,noneorfast. - Most teams run it in CI.
CI (continuous integration) is a server that automatically builds, tests and checks every change pushed to the shared repository, so nobody can forget go vet or the linters. Like a manager who re-checks every bill before closing time, every day, without being asked.
gofumpt
- "A stricter gofmt": it does everything gofmt does, plus more rules. It is a drop-in replacement (you can use it wherever you used gofmt), and running gofmt after gofumpt changes nothing.
- Some of its rules: no empty lines at the start or end of a function body; no empty lines around a lone statement in a block; standard library imports in their own group at the top.
- Install:
go install mvdan.cc/gofumpt@latest. Use:gofumpt -l -w .
goimports
- In the words of Code Review Comments, "a superset of gofmt which additionally adds (and removes) import lines as necessary". You use
strings.Fieldswithout importingstrings, and goimports adds the import; you delete the last use ofstrings, and it removes the import. So"strings" imported and not used(episode 3) almost disappears. Many editors run it on save.
The order on every change
- Format:
gofmt -l -w .(or gofumpt, or goimports). - Vet:
go vet ./... - Lint:
staticcheck ./...orgolangci-lint run. - Test:
go test ./...
Mini project: a tidy shop repository
Task:
- Lay out the shop with three programs under
cmd/(shop,report,stock) andbillingunderinternal/. - Write a package comment and a doc comment on every exported name.
- Add
ExamplePriceandExampleTotalwith// Output:. gofmt -l .prints nothing.go vet ./...reports no problems.go doc ./internal/billing.Totalreads like a good label.
Full worked solution
$ go mod init example.com/shop
go: creating new go.mod: module example.com/shop
shop/
├── go.mod
├── cmd/
│ ├── report/main.go
│ ├── shop/main.go
│ └── stock/main.go
└── internal/
└── billing/
├── billing.go
└── example_test.go
go.mod:
module example.com/shop
go 1.24.7
internal/billing/billing.go: exactly the doc-commented version from "Doc comments and go doc" (package comment, Price and Total comments, [Price] link).
internal/billing/example_test.go: exactly the file from "Examples that are tested" (ExampleTotal with // Output: 35, ExamplePrice with // Output: 0).
cmd/shop/main.go:
package main
import (
"fmt"
"example.com/shop/internal/billing"
)
func main() {
fmt.Println("counter: chai x2 =", billing.Total("chai", "chai"))
}
cmd/report/main.go:
package main
import (
"fmt"
"example.com/shop/internal/billing"
)
func main() {
fmt.Println("report: 12 samosas =", 12*billing.Price("samosa"))
}
cmd/stock/main.go: the gofmt-formatted version from the gofmt section, with "%s: %d cups left\n" (verbs in the right order).
The checks, all real:
$ go run ./cmd/shop
counter: chai x2 = 20
$ go run ./cmd/report
report: 12 samosas = 180
$ go run ./cmd/stock
chai: 12 cups left
$ gofmt -l .
$ go vet ./...
$ go test ./...
? example.com/shop/cmd/report [no test files]
? example.com/shop/cmd/shop [no test files]
? example.com/shop/cmd/stock [no test files]
ok example.com/shop/internal/billing 0.002s
$ go doc ./internal/billing.Total
package billing // import "example.com/shop/internal/billing"
func Total(items ...string) int
Total returns the bill for all the items, in rupees. Unknown items cost
nothing; see Price.
$ go build -o bin/ ./cmd/... && ls bin
report
shop
stock
gofmt -l . and go vet ./... print nothing: no unformatted files, no suspicious code. [no test files] means those packages have no _test.go files (fine for small main packages).
Expert corner
Doc comment syntax: headings, lists, code blocks, links
Since Go 1.19, doc comments have a small syntax of their own (from Go Doc Comments). A long package comment often lives in its own file, by convention doc.go:
// Package billing works out prices and bills for the chai shop.
//
// # Prices
//
// All prices are whole rupees. Items that are not on the menu
// cost 0, so a typing mistake never crashes the counter:
//
// billing.Price("masala") // 0
//
// # What you can do
//
// - price one item with [Price]
// - add up a whole order with [Total]
// - build an order step by step with [Bill]
//
// To split a typed order such as "chai samosa" into items, use [strings.Fields].
package billing
# Pricesis a heading: a line starting with#and a space, with blank lines around it.- An indented line (a tab after
//) is a code block, shown as-is. - Indented lines starting with
-form a list. [Price],[Bill]and[strings.Fields]are doc links.- A blank
//line starts a new paragraph.
$ go doc ./internal/billing
package billing // import "example.com/shop/internal/billing"
Package billing works out prices and bills for the chai shop.
# Prices
All prices are whole rupees. Items that are not on the menu cost 0, so a typing
mistake never crashes the counter:
billing.Price("masala") // 0
# What you can do
- price one item with Price
- add up a whole order with Total
- build an order step by step with Bill
To split a typed order such as "chai samosa" into items, use strings.Fields.
func Menu() map[string]int
func Price(item string) int
func Total(items ...string) int
type Bill struct{ ... }
go doc also documents types (go doc ./internal/billing.Bill) and methods:
$ go doc ./internal/billing.Bill.Add
package billing // import "example.com/shop/internal/billing"
func (b *Bill) Add(item string)
Add puts one more item on the bill.
gofmt formats comments too
gofmt rewrites doc comments into the standard syntax. A list indented with two spaces and a code block indented with two spaces:
// Package menu lists what the shop sells.
//
// Today's specials:
// - masala chai
// - bun maska
//
// Example:
// menu.Today()
package menu
$ gofmt -d menu.go
diff menu.go.orig menu.go
--- menu.go.orig
+++ menu.go
@@ -1,9 +1,10 @@
// Package menu lists what the shop sells.
//
// Today's specials:
-// - masala chai
-// - bun maska
+// - masala chai
+// - bun maska
//
// Example:
-// menu.Today()
+//
+// menu.Today()
package menu
go doc and unexported names
Without -u, go doc doesn't find a lowercase name, and the message is confusing because it tries to read billing.prices as a folder (real run, in a scratch copy of the shop):
$ go doc ./internal/billing.prices
doc: cannot find package "." in:
/tmp/notes29/mini/internal/billing.prices
exit status 1
$ go doc -u ./internal/billing.prices
package billing // import "example.com/shop/internal/billing"
var prices = map[string]int{"chai": 10, "samosa": 15}
Why the external test package matters for examples
An example in package billing_test must write billing.Total(...), exactly as a user would. That is the code pkg.go.dev shows, so it can be copied straight into a real program. An example in package billing could call unexported helpers that no reader can use.
Vet in CI
Because go vet exits with status 1 when it finds something (the shell's $? was 1 in our runs, 0 for a clean module), it can fail a CI job. Teams usually run: test -z "$(gofmt -l .)" (fails if any file needs formatting), go vet ./..., the linters, then go test ./....
Common mistakes (and the real messages)
| Mistake | Real message | Why | Fix |
|---|---|---|---|
main.go + report.go, both with func main |
main redeclared in this block |
one folder = one package = one main | cmd/shop/, cmd/report/ |
importing another module's internal/ |
use of internal package example.com/shop/internal/billing not allowed |
internal is private to its parent tree | import only public packages |
// Output: 30 while the code prints 35 |
--- FAIL: ExampleTotal (0.00s) got: 35 want: 30 |
the example is out of date | fix the code or the comment |
// Output: on a map loop |
--- FAIL: ExampleMenu with lines in a different order |
map order is random | // Unordered output: |
ExampleTotl |
ExampleTotl refers to unknown identifier: Totl |
the name must match a real identifier | ExampleTotal |
ExampleTotal_Masala |
ExampleTotal_Masala refers to unknown field or method: Total.Masala |
a capital suffix means a method | ExampleTotal_masala |
fmt.Printf("%d", item), item a string |
fmt.Printf format %d has arg item of wrong type string (output: %!d(string=chai)) |
verb doesn't match the value | %s for strings, %d for ints |
| two verbs, one value | fmt.Printf format %d reads arg #2, but call has 1 arg (output: %!d(MISSING)) |
missing argument | pass every value |
fmt.Println("cups: %d", cups) |
fmt.Println call has possible Printf formatting directive %d |
Println doesn't use verbs | fmt.Printf |
passing a struct with a sync.Mutex by value |
report passes lock by value: ... contains sync.Mutex |
the copy has its own lock | pass a pointer |
code after return |
unreachable code |
it can never run | delete it |
| blank line between comment and func | (no message) go doc shows no comment |
not directly before the declaration | no blank line in between |
go doc ./internal/billing.prices |
doc: cannot find package "." in: ... |
lowercase names are hidden | go doc -u |
comment // Calculates the bill |
(no message) | doesn't start with the name | // Total returns ... |
Practice
- to 4. (Homework from the video) Restructure a program into
cmd/andinternal/; write doc comments and read them withgo doc; add an example, break its// Output:, and read the failure; plant a Printf bug and catch it withgo vet ./.... - What does this program print, and what does
go vetsay?
package main
import "fmt"
func main() {
stock := "twelve"
fmt.Printf("%d cups in stock\n", stock)
fmt.Println("done")
}
- Write a second example of
Totalthat shows the bill for no items, named so that it appears underTotal. - Name the example function for the method
Sumof typeBill, and say what happens if it has no output comment. - Fix the style of this code following Go Code Review Comments:
// this function adds an item
func (self *Bill) Add(item string) error {
if item == "" {
return errors.New("Empty item!")
}
self.items = append(self.items, item)
return nil
}
- A team has one program and no shared code. Which layout from "Organizing a Go module" fits? Should they add
pkg/? - Which tool would you use to (a) see only the list of unformatted files, (b) see what gofmt would change, (c) add a missing import automatically?
Solutions
-
to 4. See the mini project for the layout and the real outputs; the failing example and the vet message are shown in the sections above.
-
It compiles and runs (real output):
%!d(string=twelve) cups in stock
done
and go vet reports (real output):
$ go vet .
# example.com/p1
# [example.com/p1]
./main.go:7:2: fmt.Printf format %d has arg stock of wrong type string
- A suffix starting with a lower-case letter:
func ExampleTotal_empty() {
fmt.Println(billing.Total())
// Output: 0
}
$ go test -v -run 'ExampleTotal' ./internal/billing
=== RUN ExampleTotal
--- PASS: ExampleTotal (0.00s)
=== RUN ExampleTotal_unknown
--- PASS: ExampleTotal_unknown (0.00s)
=== RUN ExampleTotal_empty
--- PASS: ExampleTotal_empty (0.00s)
PASS
ok example.com/shop/internal/billing 0.002s
(-run 'ExampleTotal' runs only the tests and examples whose names match.)
-
ExampleBill_Sum. Without an output comment it is compiled but not run: it never appears ingo test -v(see the real run in "Example naming"). -
The comment must start with the name; the receiver should be short, not
self; the error string should be lower case with no punctuation:
// Add puts one more item on the bill.
// It returns an error if item is empty.
func (b *Bill) Add(item string) error {
if item == "" {
return errors.New("empty item")
}
b.items = append(b.items, item)
return nil
}
-
The "basic command":
main.goat the module root. Nopkg/: the guide never uses it, and with one program there is nothing to organise. Addcmd/when a second program appears andinternal/when code is shared. -
(a)
gofmt -l ., (b)gofmt -d file.go, (c) goimports (or an editor that runs it on save).
Quick quiz
1. Which doc comment follows the Go convention? (From the video.)
// A: Calculates the bill
// B: Total returns the bill for all the items, in rupees.
// C: this function returns total
// D: TODO
func Total(items ...string) int
Answer
B. A full sentence that begins with the name being documented, Total, and says what it returns.
2. go run . in a folder with main.go and report.go, both package main with a func main, gives what?
Answer
main redeclared in this block: one folder is one package, and one program has one main. Use cmd/shop/ and cmd/report/.
3. True or false: the compiler rejects fmt.Printf("%d", "chai").
Answer
False. It compiles and prints %!d(string=chai). go vet catches it: fmt.Printf format %d has arg ... of wrong type string.
4. Which of these checks does go test run automatically: printf, copylocks, unreachable?
Answer
Only printf. It is in the high-confidence subset (atomic, bool, buildtags, directive, errorsas, ifaceassert, nilfunc, printf, stringintconv, tests). The real vetzoo run showed go test reporting only the two Printf problems.
5. Another module imports example.com/shop/internal/billing. What happens?
Answer
The go tool refuses: use of internal package example.com/shop/internal/billing not allowed.
6. An example ranges over a map and prints each entry. Which comment should it use?
Answer
// Unordered output:, because map order is random. With // Output: it fails whenever the order differs (real run above).
Interview questions
- How do you lay out a Go repository with several programs? One folder per program under
cmd/<name>/, each apackage main; shared code ininternal/so no other module can import it; public packages at the module root or in plain folders. Build all withgo build -o bin/ ./cmd/.... - What is your view on
pkg/? It's a common convention, not a Go rule. The go.dev "Organizing a Go module" guide doesn't use it; it lengthens import paths and adds no protection (onlyinternal/is enforced). Start simple; follow the team's existing convention if there is one. - What makes a good doc comment? Directly above the declaration, no blank line; full sentences starting with the name; says what it returns, including edge cases; "reports whether" for booleans; a package comment starting "Package name" in one file; doc links like
[Price]for related names. - What are example functions and why use them? Functions named
ExampleXxxin_test.gofiles, with// Output:(or// Unordered output:) comments.go testruns them and compares output, so they are documentation that can't go stale, and pkg.go.dev shows them next to the docs. - What is the difference between gofmt, go vet and a linter? gofmt changes only formatting. go vet does static analysis for code that compiles but is almost certainly wrong (Printf mismatches, copied locks, unreachable code). Linters like staticcheck add many more checks for bugs, dead code, performance and style.
- Does
go testreplacego vet? No. go test runs only a high-confidence subset of vet checks;copylocksandunreachable, for example, are not in it. Rungo vet ./...separately, typically in CI. - What does golangci-lint add over running tools one by one? It's a "linters runner": one command and one config file run many linters (and, in v2, formatters via
golangci-lint fmt), which makes it easy to enforce the same checks locally and in CI. - Why use an external test package (
package billing_test) for examples? It can use only exported names, exactly like real users, so the example code shown in the docs is copy-pasteable.
Glossary
| Term | Meaning | Example |
|---|---|---|
| Project | all the code, programs and files for one piece of software | the chai shop repository |
| Repository | a folder of code tracked by Git, often hosted on GitHub | github.com/you/shop |
| GitHub | a website that hosts Git repositories | where you see pkg/ folders |
| Commit | a saved snapshot of changes in Git | "run go vet before every commit" |
| Code review | a teammate reading your change before it is accepted | Code Review Comments come from these |
| Package | a folder of .go files compiled together (episode 27) |
internal/billing |
package main |
the package that becomes a runnable program; needs one func main |
cmd/shop/main.go |
| Redeclared | the same name declared twice in one place | main redeclared in this block |
| Module | a project with a go.mod file at the top (episode 28) |
module example.com/shop |
| Module path | the module's name in go.mod, prefix of its import paths |
example.com/shop |
| Module root | the folder that contains go.mod |
shop/ |
| Import path | module path + folder; how a package is imported | example.com/shop/internal/billing |
| Command | a runnable program (a package main) |
shop, report, stock |
cmd/ layout |
one folder per program under cmd/ |
cmd/report/main.go |
internal/ layout |
shared code under internal/, importable only inside its parent tree |
internal/billing |
pkg/ debate |
whether to put importable packages under pkg/; optional, not used by the go.dev guide |
example.com/shop/pkg/billing |
| "Organizing a Go module" | the official go.dev guide to module layouts | basic command, multiple commands |
| Server project | a program nobody imports; logic in internal/, programs in cmd/ |
a shop web server |
./... pattern |
"this folder and every folder below it" | go vet ./... |
./cmd/... |
every package below cmd/ |
go build -o bin/ ./cmd/... |
go build -o bin/ |
build and put the programs in folder bin/ |
bin/shop |
go list |
prints the import paths of packages | go list ./... |
replace directive |
a go.mod line pointing a module path at a folder (episode 28) |
replace example.com/shop => ../shop |
| Signature | a function's name, parameters and results | func Price(item string) int |
| Exported name | starts with a capital letter; usable from other packages | Price |
| Unexported name | starts with a lower-case letter; only inside its package | prices |
| Top-level declaration | a declaration outside any function | func Price, var prices |
| Doc comment | a comment directly before a top-level declaration, no blank line | // Price returns ... |
| Package comment | the doc comment before package, starting "Package name" |
// Package billing works out ... |
doc.go |
conventional file holding a long package comment | internal/billing/doc.go |
| "reports whether" | the wording for functions that return a bool | // IsOpen reports whether ... |
| Doc link | a name in square brackets in a doc comment, made clickable | [Price], [strings.Fields] |
| Heading (doc comment) | a # line in a doc comment (Go 1.19+) |
// # Prices |
| Code block (doc comment) | an indented line in a doc comment, shown as-is | // billing.Price("masala") |
| List (doc comment) | indented lines starting with - |
// - price one item |
go doc |
prints documentation in the terminal | go doc ./internal/billing.Price |
go doc -all |
documentation of the whole package | go doc -all ./internal/billing |
go doc -src |
the source code of a name | go doc -src ./internal/billing.Price |
go doc -u |
also show unexported names | go doc -u ./internal/billing |
go doc -short |
one line per name | go doc -short ./internal/billing |
| gopls | the Go language server that powers editors' hover docs and more | VS Code hover |
| pkg.go.dev | "a website for discovering and evaluating Go packages and modules" | github.com/google/uuid page |
| Stale | out of date, no longer true | an old comment |
_test.go file |
a file compiled only by go test |
example_test.go |
| Example function | ExampleXxx() in a test file; run and checked by go test |
ExampleTotal |
// Output: |
the expected output of an example, compared by go test |
// Output: 35 |
// Unordered output: |
expected lines in any order | map loop example |
Example() |
an example for the whole package | func Example() |
Example_suffix naming |
a further example, suffix starts lower case | ExampleTotal_unknown |
ExampleT_Method naming |
an example for a method of a type | ExampleBill_Add |
| External test package | package name_test in the same folder; uses the package from outside |
package billing_test |
go test -v |
verbose: list every test and example | === RUN ExampleTotal |
go test -run |
run only tests and examples whose names match | -run ExampleMenu |
go test -count |
run tests this many times | -count=10 |
| Map order | the random order in which range visits a map |
chai or samosa first |
| Effective Go | the go.dev guide to writing clear, idiomatic Go | — |
| Idiomatic | written the way experienced Go programmers naturally write it | b *Bill, not self *Bill |
| Go Code Review Comments | "a supplement to Effective Go"; "a laundry list of common mistakes, not a style guide" | Error Strings, Receiver Names |
| Error string rule | lower case, no punctuation at the end | errors.New("item not found") |
| Receiver name | the name of a method's receiver; short, not self/this |
b in func (b *Bill) Add |
| gofmt | Go's standard formatter | gofmt -w main.go |
gofmt -l |
list files that need formatting | cmd/stock/main.go |
gofmt -d |
show the diff, change nothing | - cups := 12 |
gofmt -w |
write the formatted code into the file | gofmt -w cmd/stock/main.go |
go fmt |
go command shortcut running gofmt on packages | go fmt ./... |
| Diff | the differences between two versions: - removed, + added |
+ cups := 12 |
| Format string | the first argument of Printf, with verbs |
"%s: %d cups left\n" |
| Verb | a % code saying how to print a value |
%s string, %d integer |
%!d(string=chai) |
fmt's mark for a verb that got the wrong type | wrong %d |
%!d(MISSING) |
fmt's mark for a verb with no value | too few arguments |
| go vet | Go's built-in checker for suspicious code | go vet ./... |
| Static analysis | checking code by reading it, without running it | go vet, staticcheck |
| Analyzer | one check inside go vet | printf, copylocks |
| Heuristic | a good guess that is usually right | vet's reports |
Lock / sync.Mutex |
lets one goroutine at a time use some data; must not be copied | mu sync.Mutex |
| Self-assignment | assigning a variable to itself | cups = cups |
| Unreachable code | code that can never run | a line after return |
-vet=off |
go test flag that skips its vet checks |
go test -vet=off . |
| Linter | a tool that reports bugs, dead code and style problems | staticcheck |
| Dead code | code that is never used or never runs | unreachable lines |
| staticcheck | "go vet on steroids"; checks grouped SA1 to SA9 | staticcheck ./... |
| golangci-lint | "Smart, fast linters runner" | golangci-lint run |
golangci-lint fmt |
runs formatters; -d shows a diff |
golangci-lint fmt -d |
--fix |
apply suggested fixes | golangci-lint run --fix |
formatters section |
golangci-lint v2 config section for formatters | v2, 23 March 2025 |
--default |
golangci-lint's starting set of linters | standard, all, none, fast |
| gofumpt | "a stricter gofmt", drop-in replacement | gofumpt -l -w . |
| Drop-in replacement | a tool you can use exactly where the old one was used | gofumpt for gofmt |
| goimports | gofmt that also adds and removes import lines | adds "strings" |
go install |
builds a program and installs it in your Go bin folder | go install mvdan.cc/gofumpt@latest |
tool directive |
a go.mod line pinning a tool's version (episode 28) |
a linter pinned for the whole team |
| CI | continuous integration: a server that checks every change automatically | runs go vet and linters |
| Exit status | a number a program returns: 0 success, non-zero failure | go vet exits 1 on problems |
Summary
- One folder is one package, so two
func mainin one folder givemain redeclared in this block. Give each program its own folder:cmd/<name>/main.go. - Shared private code goes in
internal/: any package of this module may import it, no other module can (use of internal package ... not allowed). The go.dev guide says keep packages in internal as much as possible. pkg/is optional and debated; the go.dev guide never uses it. Start with one folder, addcmd/andinternal/when needed../...means this folder and everything below;go build -o bin/ ./cmd/...builds every program.- Doc comments sit directly above top-level declarations, are full sentences starting with the name, and every exported name should have one. The package comment starts "Package billing".
[Price]is a doc link. Headings, lists and code blocks have their own syntax, and gofmt keeps it tidy. go docreads them in the terminal (-all,-src,-u,-short); pkg.go.dev shows them, with examples, on the web.- Example functions (
ExampleTotal,ExampleBill_Add,ExampleTotal_unknown,Example) with// Output:or// Unordered output:are documentation thatgo testchecks: wrong docs fail withgot:/want:. - Learn the style from Effective Go and Go Code Review Comments: comment sentences, lower-case error strings, short receiver names, no panic for normal errors.
- gofmt
-llists,-dshows a diff,-wfixes. go vet finds code that compiles but is wrong (Printf mismatches, copied locks, unreachable code);go testruns only a subset of its checks. - On top: staticcheck ("go vet on steroids"), golangci-lint (a linters runner, usually in CI), gofumpt (a stricter gofmt) and goimports (gofmt plus imports). Format, vet, lint, test: on every change.
Next episode: Generics part 1: type parameters. One function for ints, floats and strings: type parameters, constraints, any, comparable, and a Stack[T].