Go Patterns
Full bibliography: references/sources.md.
Iron Law
ERRORS ARE VALUES [5][7]
Never ignore errors.
if err != nilis correctness, not boilerplate. Every error
return must be checked, wrapped with context, or explicitly documented as intentionally
ignored with
_ = fn(). "Errors are values. Values can be programmed." — Rob Pike [5]
Error Handling
- Wrap with context,
return fmt.Errorf("finding user %s: %w", id, err), not a barereturn err: the caller loses context. - Declare sentinel errors (
var ErrNotFound = errors.New("not found")) and match them witherrors.Is. - Never discard an error with
val, _ := fn(): check it, wrap it, or ignore it on purpose with_ = fn(). - No
panicorlog.Fatalin library code.
Interface Design
- Accept interfaces:
NewService(repo Repository), notNewService(repo *PostgresRepo). - Define an interface at the consumer when it is used, not at the producer before use.
- Keep interfaces small (1-3 methods) and compose them (
ReadWriterembedsReaderandWriter).
Concurrency
- Do not communicate by sharing memory; share memory by communicating.
- Pass
context.Contextas the first parameter. - Give every goroutine a clear lifecycle and cancellation, for example
errgroup.WithContext. A barego fn()leaks. - Specify channel direction in signatures:
chan<- int,<-chan int.
Package Design and Zero Values
- Organize packages by domain (
user/,order/), not by type (models/,controllers/). Keep internals unexported. - Make zero values ready to use (
sync.Mutex,bytes.Buffer; a zeroTimeoutmeans no timeout). - No naked
returnin functions with named returns. - No complex
init()with side effects.
Extended References
references/sources.md— Full bibliographyreferences/violations.md— Violations with citationsreferences/patterns.md— Extended patterns with citationsreferences/detection.md— Grep patterns for automated detectionreferences/concurrency.md— CSP-grounded concurrency patterns