Global state
Package-level state is sometimes useful, but it should be small, explicit, and hard to misuse; hidden mutable globals age badly.
Canonical guidance
- prefer explicit state passed through ordinary values and constructors
- keep package-level state small and obvious when it exists
- default instances should be thin conveniences, not the only practical API
Use when
- reviewing singleton-like packages
- deciding whether package vars are appropriate
- hardening tests against cross-case leakage
Avoid
- hidden mutable globals that change behavior far from the call site
- package state that makes tests order-dependent
- global knobs when explicit instances would compose better
Preferred pattern
var DefaultClient = &Client{}
Anti-pattern
- exposing only one mutable package-global instance and forcing every caller and test through it
Explanation: This is tempting because it removes wiring, but it also removes isolation and makes behavior harder to reason about.
Why
- Google’s global-state guidance is a useful complement to Go’s usual preference for explicit wiring and small packages
Related pages
Sources
- Organizing Go code - Andrew Gerrand
- Google Go Best Practices - Google