Canonical Go Best Practices
These standards define "Canonical Go" style. They complement Effective Go and Google's Go style guidelines. All new code must abide by go fmt and go vet.
For full code examples of every rule, see examples.md.
Cosmetic Discipline
Braces
- No extra newlines between braces. Use compact struct/slice literal style:
tests := []struct{
name string
}{{
name: "foo",
}, {
name: "bar",
}}
Spacing (blank lines)
Use blank lines semantically, not aesthetically. Rules:
- Declaration + immediate use/check = no blank line (strongly associated)
- Declaration used across multiple blocks = blank line after declaration
- Declaration + check (≤3 lines) = no blank line; check >3 lines = blank line after
// GOOD: declaration and check are strongly associated
x, err := foo()
if err != nil {
return nil, err
}
Grouping
- Don't interleave unrelated code. Group strongly interdependent sections.
- Declare closures close to where they're used if they capture values.
- If no captures needed, define at top of highest scope to make that obvious.
- Consider whether a closure is needed at all — prefer simple top-to-bottom flow.
Naming Discipline
Names should:
- Say what they mean —
copy(dest, source) not copy(x, y)
- Have consistent word order — if the API uses
verbNoun, keep using verbNoun
- Be concise — shorter is better when unambiguous
- Use simple words — prefer short common words over long rare ones
- Be unified — one name per concept across the codebase
- Avoid including types —
needle not needleString (unless disambiguating)
- Use US spelling (company policy)
If a good name can't be found, the API probably needs refactoring.
Take extreme care with exported names — they can't be changed without breaking consumers.
Error Discipline
Error messages
- Start with a lowercase verb, usually prefixed with "cannot"
- Keep messages concise and consistently phrased
- Lowercase first letter (errors may be wrapped, capitals mid-line look bad)
- Uppercase for acronyms (TCP, OS) and product names (LXD)
- Tailor message detail to the expected reader (developer vs end-user)
- Avoid repeating context that will be added by wrapping higher up the stack
// GOOD
return fmt.Errorf("cannot connect to %s: %v", addr, err)
// BAD
return fmt.Errorf("Connection to server failed: %v", err)
Custom error types
- Use custom error types only when the caller can take specific recovery action.
- Add public fields to expose data needed for error handling decisions.
- For unrecoverable errors, use
errors.New or fmt.Errorf.
Error wrapping: %w vs %v
%w (wrap): Use when consumers should be able to inspect/match the inner error via errors.Is/errors.As. Beware: this makes the inner error part of your public API.
%v (paste): Use for unrecoverable errors where consumers should not inspect the inner error. This is the safer default.
- Don't wrap at every function boundary — only at meaningful abstraction layer boundaries. Over-wrapping produces long, low-information error chains that expose stack internals.
Panic calmly
- Prefer
error returns over panics.
- Panics are acceptable when:
- The caller misused the API (prefix with
internal error:)
- Error handling is impossible (e.g.,
init functions, global var declarations)
- Provide
Foo() (Value, error) + MustFoo() Value pairs when both contexts are needed.
- Use
panic("unreachable") to mark logically impossible code paths (rare, but makes control flow explicit).
Code Discipline
Pyramids of doom
- Max 3 levels of indentation. Refactor deeper nesting into functions.
- Convert error-returning branches into early-return preconditions.
Inline if
if err := fn(); err != nil is fine for short expressions.
- If the initializer is long/multi-line, break it out into a separate statement.
Variable declaration
Prefer in this order:
foo := expr — default choice, even for explicit zero values (signals the zero value may be read before reassignment)
var foo type — when the zero value is never read before assignment
var foo = expr — avoid (verbose, no advantage over :=)
var foo type = expr — avoid (verbose; use foo := type(expr) for type assertion)
Put var declarations first, don't mingle with :=.
Interface implementation assertion
Use compile-time checks when a type must implement an interface:
var _ io.Reader = &MyFile{}
var _ io.Writer = &MyFile{}
Struct population (unexported)
- Always use named fields (never anonymous initialization)
- Match variable names to field names when copying values
- Either compute all fields inline OR pre-compute all into variables — no mixing
- Keep field order consistent with the type definition
- Single-line structs: only if ≤~25 characters of fields
Struct population (exported)
- Don't expose structs for direct population — use setter/builder methods instead.
- Exception: parameter/option structs where users pass data (not touch internals).
Comments
- Comments should explain why, not what (the code already says what).
- Sentences end with a full stop.
- Implementation details go in function body comments, not doc comments.
- Use top-of-file comments to tie together complex cross-function patterns.
Global state
- Almost never use global state. If you think you need it, you almost certainly don't.
Function Discipline
Function docs
- Start doc comment with the function name:
// Foo transforms...
- 1-2 concise sentences covering purpose and when/why to use it.
- Don't list parameters (names+types should be self-explanatory). Don't describe implementation.
- Use "the" (definite article) when referring to parameters, not "a".
- All exported functions require doc comments. Unexported functions used across files require them unless trivial.
- Don't document who calls a function — document what it does.
Function naming
- Getters are nouns; other functions contain verbs.
- Maintain consistent word order with surrounding API.
- Watch for noun/verb ambiguity:
SizeEstimate (getter) vs EstimateSize (action).
Nil arguments
- Don't defensively nil-check every nillable argument — that's the caller's responsibility.
- If nil is valid/optional, document it and check for it.
Passing structs
- Prefer pointer parameters and return values for structs:
- Promotes consistent types and semantics across the API
- Allows optional parameters
return nil, err is clearer than return SomeStruct{}, err
Return values
- Return computed values, don't take output pointers (this isn't C).
- When error is nil → return valid values. When error is non-nil → return zero values.
return nil, nil is misleading. return foo, err (non-nil both) is misleading.
Return value naming
- Name returns when it adds information.
ok for success booleans, err for errors.
- Don't name when redundant:
(err error) adds nothing over error.
Receivers
- Always name receivers, even when unused (consistency).
- Use consistent receiver types — always pointer OR always value, not mixed.
- Avoid nil receiver patterns; use a helper function instead.
Bare returns
- Don't use bare returns. They sacrifice clarity for brevity.
- Exception: deferred functions that must modify named return values (rare, born of necessity).
Test Discipline
- Tests should be self-contained — no ordering dependencies between tests.
- Use table-driven tests to share setup/teardown across similar cases.
- Use zero values for "not applicable" fields (e.g., omit
expectedOutput when expectedError is set).
- Group happy-path tests first, error tests last.
- Don't over-abstract test helpers — readers shouldn't need to study a test API to understand tests.
- Compact brace style for test table entries (see examples.md).
tests := []struct{
name string
input any
expect string
}{{
name: "valid input",
input: 123,
}, {
name: "invalid input",
input: nil,
expect: "input required",
}}
1---2name: go-standards3description: Canonical Go coding standards and best practices. Use when writing, reviewing, or refactoring Go code. Covers formatting, naming, errors, functions, structs, interfaces, and testing conventions.4argument-hint: [topic]5license: default6compatibility: universal7allowed-tools: Read Grep Glob8metadata:9 source: https://skillmd.com/skills/tonyandrewmeyer/go-standards10---1112# Canonical Go Best Practices1314These standards define "Canonical Go" style. They complement [Effective Go](https://go.dev/doc/effective_go) and [Google's Go style guidelines](https://google.github.io/styleguide/go/decisions). All new code must abide by `go fmt` and `go vet`.1516For full code examples of every rule, see [examples.md](examples.md).1718---1920## Cosmetic Discipline2122### Braces23- No extra newlines between braces. Use compact struct/slice literal style:24```go25tests := []struct{26 name string27}{{28 name: "foo",29}, {30 name: "bar",31}}32```3334### Spacing (blank lines)35Use blank lines **semantically**, not aesthetically. Rules:36- Declaration + immediate use/check = **no** blank line (strongly associated)37- Declaration used across multiple blocks = blank line after declaration38- Declaration + check (≤3 lines) = no blank line; check >3 lines = blank line after3940```go41// GOOD: declaration and check are strongly associated42x, err := foo()43if err != nil {44 return nil, err45}46```4748### Grouping49- Don't interleave unrelated code. Group strongly interdependent sections.50- Declare closures close to where they're used if they capture values.51- If no captures needed, define at top of highest scope to make that obvious.52- Consider whether a closure is needed at all — prefer simple top-to-bottom flow.5354---5556## Naming Discipline5758Names should:59- **Say what they mean** — `copy(dest, source)` not `copy(x, y)`60- **Have consistent word order** — if the API uses `verbNoun`, keep using `verbNoun`61- **Be concise** — shorter is better when unambiguous62- **Use simple words** — prefer short common words over long rare ones63- **Be unified** — one name per concept across the codebase64- **Avoid including types** — `needle` not `needleString` (unless disambiguating)65- **Use US spelling** (company policy)6667If a good name can't be found, the API probably needs refactoring.6869Take **extreme** care with exported names — they can't be changed without breaking consumers.7071---7273## Error Discipline7475### Error messages76- Start with a lowercase verb, usually prefixed with "cannot"77- Keep messages concise and consistently phrased78- Lowercase first letter (errors may be wrapped, capitals mid-line look bad)79- Uppercase for acronyms (TCP, OS) and product names (LXD)80- Tailor message detail to the expected reader (developer vs end-user)81- Avoid repeating context that will be added by wrapping higher up the stack8283```go84// GOOD85return fmt.Errorf("cannot connect to %s: %v", addr, err)8687// BAD88return fmt.Errorf("Connection to server failed: %v", err)89```9091### Custom error types92- Use custom error types **only** when the caller can take specific recovery action.93- Add public fields to expose data needed for error handling decisions.94- For unrecoverable errors, use `errors.New` or `fmt.Errorf`.9596### Error wrapping: `%w` vs `%v`97- **`%w`** (wrap): Use when consumers should be able to inspect/match the inner error via `errors.Is`/`errors.As`. Beware: this makes the inner error part of your public API.98- **`%v`** (paste): Use for unrecoverable errors where consumers should not inspect the inner error. This is the safer default.99- Don't wrap at every function boundary — only at meaningful abstraction layer boundaries. Over-wrapping produces long, low-information error chains that expose stack internals.100101### Panic calmly102- Prefer `error` returns over panics.103- Panics are acceptable when:104 - The caller misused the API (prefix with `internal error:`)105 - Error handling is impossible (e.g., `init` functions, global `var` declarations)106- Provide `Foo() (Value, error)` + `MustFoo() Value` pairs when both contexts are needed.107- Use `panic("unreachable")` to mark logically impossible code paths (rare, but makes control flow explicit).108109---110111## Code Discipline112113### Pyramids of doom114- Max 3 levels of indentation. Refactor deeper nesting into functions.115- Convert error-returning branches into early-return preconditions.116117### Inline `if`118- `if err := fn(); err != nil` is fine for short expressions.119- If the initializer is long/multi-line, break it out into a separate statement.120121### Variable declaration122Prefer in this order:1231. `foo := expr` — default choice, even for explicit zero values (signals the zero value may be read before reassignment)1242. `var foo type` — when the zero value is never read before assignment1253. `var foo = expr` — avoid (verbose, no advantage over `:=`)1264. `var foo type = expr` — avoid (verbose; use `foo := type(expr)` for type assertion)127128Put `var` declarations first, don't mingle with `:=`.129130### Interface implementation assertion131Use compile-time checks when a type must implement an interface:132```go133var _ io.Reader = &MyFile{}134var _ io.Writer = &MyFile{}135```136137### Struct population (unexported)138- Always use named fields (never anonymous initialization)139- Match variable names to field names when copying values140- Either compute all fields inline OR pre-compute all into variables — no mixing141- Keep field order consistent with the type definition142- Single-line structs: only if ≤~25 characters of fields143144### Struct population (exported)145- Don't expose structs for direct population — use setter/builder methods instead.146- Exception: parameter/option structs where users pass data (not touch internals).147148### Comments149- Comments should explain **why**, not **what** (the code already says what).150- Sentences end with a full stop.151- Implementation details go in function body comments, not doc comments.152- Use top-of-file comments to tie together complex cross-function patterns.153154### Global state155- Almost never use global state. If you think you need it, you almost certainly don't.156157---158159## Function Discipline160161### Function docs162- Start doc comment with the function name: `// Foo transforms...`163- 1-2 concise sentences covering purpose and when/why to use it.164- Don't list parameters (names+types should be self-explanatory). Don't describe implementation.165- Use "the" (definite article) when referring to parameters, not "a".166- All exported functions require doc comments. Unexported functions used across files require them unless trivial.167- Don't document who calls a function — document what it does.168169### Function naming170- Getters are nouns; other functions contain verbs.171- Maintain consistent word order with surrounding API.172- Watch for noun/verb ambiguity: `SizeEstimate` (getter) vs `EstimateSize` (action).173174### Nil arguments175- Don't defensively nil-check every nillable argument — that's the caller's responsibility.176- If nil is valid/optional, document it and check for it.177178### Passing structs179- Prefer pointer parameters and return values for structs:180 - Promotes consistent types and semantics across the API181 - Allows optional parameters182 - `return nil, err` is clearer than `return SomeStruct{}, err`183184### Return values185- Return computed values, don't take output pointers (this isn't C).186- When error is nil → return valid values. When error is non-nil → return zero values.187- `return nil, nil` is misleading. `return foo, err` (non-nil both) is misleading.188189### Return value naming190- Name returns when it adds information. `ok` for success booleans, `err` for errors.191- Don't name when redundant: `(err error)` adds nothing over `error`.192193### Receivers194- Always name receivers, even when unused (consistency).195- Use consistent receiver types — always pointer OR always value, not mixed.196- Avoid nil receiver patterns; use a helper function instead.197198### Bare returns199- Don't use bare returns. They sacrifice clarity for brevity.200- Exception: deferred functions that must modify named return values (rare, born of necessity).201202---203204## Test Discipline205206- Tests should be self-contained — no ordering dependencies between tests.207- Use table-driven tests to share setup/teardown across similar cases.208- Use zero values for "not applicable" fields (e.g., omit `expectedOutput` when `expectedError` is set).209- Group happy-path tests first, error tests last.210- Don't over-abstract test helpers — readers shouldn't need to study a test API to understand tests.211- Compact brace style for test table entries (see [examples.md](examples.md)).212213```go214tests := []struct{215 name string216 input any217 expect string218}{{219 name: "valid input",220 input: 123,221}, {222 name: "invalid input",223 input: nil,224 expect: "input required",225}}226```