Idioms and Gotchas
Patterns and pitfalls every Go codebase hits. Results appear in the same fence: same-line // comments when short, multiline // blocks below the sample when not.
Search across all documentation pages
Patterns and pitfalls every Go codebase hits. Results appear in the same fence: same-line // comments when short, multiline // blocks below the sample when not.
Functions accept interfaces, return concrete types.
// func Save(s Store) errorCopy slices before returning internal state.
// out := make([]T, len(in)); copy(out, in); return outGo 1.22+ per-iteration vars.
// for _, v := range xs { go f(v) } // ok in 1.22+nil slice encodes null; empty encodes [].
b, _ := json.Marshal([]int(nil))
string(b) // "null"Always provide an exit path.
// select { case <-ctx.Done(): return; case ch <- v: }defer runs at function end - wrap loop bodies.
// for ... { func(){ defer f.Close(); ... }() }Optional config via options.
// type Option func(*Server)Always set HTTP client/server timeouts.
// &http.Client{Timeout: 10 * time.Second}Return error from public APIs.
// if id == "" { return fmt.Errorf("id required") }Pass ctx into methods each call.
// func (s *Svc) Get(ctx context.Context, id string)Never copy a Mutex - share by pointer.
// type S struct { mu sync.Mutex }Map iteration order is randomized.
// do not rely on map range orderRetry only idempotent ops with backoff.
// if temporary(err) { sleep; retry }Codegen as a first-class step.
// //go:generate mockgen ...Branch with errors.Is/As, not string contains.
// errors.Is(err, ErrNotFound)Stack versions: Go 1.26.x · chi/gin/echo latest (verify at build)
Reviewed by Chris St. John·Last updated Jul 18, 2026