1. Scope
These practices assume Go 1.27 language semantics, runtime defaults, and the default experiment configuration.
2. Route to concept files
Route by the code and task in scope, focusing on changed code for a change or diff. The index combines topics and illustrative code patterns. X, T, x, and v represent any name. Open every matching reference, including the additional routes below.
Find a practice by the ID prefix in its heading and cite its full ID. Follow Practice, use Example as the idiom, and consult Why, Exceptions, and Tradeoff for mechanisms, applicability, and costs. Signals identify potentially missing practices.
Also open these references for missing safeguards or symptoms:
- Module or file language-version mismatches, build constraints, or runtime behavior overrides: MOD.
- Code that checks or drops an
error: ERH. - Goroutines or channels: CTX, GOR, and SHR.
- Blocking I/O (network, database, HTTP, files) or an HTTP handler: CTX.
- Tests of concurrent code: TBA and TST.
- Memory or goroutine count that grows: PRO and MRT.
- High GC CPU, or a program in a container: BRT, PRO, and TRC.
- A hot path, or a request to make code faster: PRO, ALO, and BEN.
2.1 Language
- CST code-structure.md: shadowing, package/built-in names (
url,len,new,max), early returns (elseafter return),func init(). - STD struct-design.md: getters/setters (
GetX/SetX), embedding (sync.Mutex), promoted-field literals, functional options (NewXWithY,Configarguments),new(expr)and pointer helpers (ptr[T],intPtr). - INT interfaces.md: interface creation/ownership, single-implementation interfaces, concrete vs interface results,
any/interface{}, typed nil interfaces/errors. - GEN generics.md: type parameters (
[T any]), constraints (comparable,~int,~string,cmp.Ordered,golang.org/x/exp/constraints), inference, generic methods, self-referential constraints. - FNM functions-and-methods.md: value/pointer or mixed receivers, mutex-bearing value receivers, named results (
n int, err error), naked returns. - LOP loops.md: range copies (
v.field =), expression evaluation, per-iteration variables (v := v,&v, goroutine closures),range n,for i := 0; i <,slices.Backward, labeled breaks,breakinsideswitch/select. - ITR iterators.md: iterator consumption/creation,
iter.Seq/iter.Seq2(including parameters),yield,iter.Pull,Next()/Value(), methods returning all elements as slices,slices.Collect. - DEF defer-and-cleanup.md:
deferin loops, deferred argument/receiver evaluation,io.Closercleanup (defer f.Close(),resp.Body,rows.Close()),Close/Syncerrors,os.Create.
2.2 Data
- NUM numbers.md: octal (
0644), integer overflow (int32(,math.MaxInt), float==, NaN/Inf,math.FMA. - SLC slices.md: length/capacity,
appendaliasing, preallocation (make([]), nil/empty ([]T{},s == nil),lenchecks,copy/slices.Clone,[low:high:max], slice-to-array conversion. - COL collection-helpers.md:
min/max,slicesinsert/delete/sort/search,maps,cmp,clear. Older forms:sort.Slice,math.Min/math.Max,append(s[:i], s[i+1:]...), map-clearingdeleteloops. - MAP maps.md: map sizing (
make(map,map[K]V{}), sorted keys (maps.Keys,sort.Strings), writes during map iteration. - MRT memory-retention.md: caches/long-lived maps (map beside mutex, deletion, post-peak size), retained substrings/subslices, zeroing dropped pointers,
strings.Clone/bytes.Clone,runtime.AddCleanup/runtime.SetFinalizer,unique.*,weak.*. - CMP comparison.md: comparable types (
==on interfaces/structs,[T comparable]),slices.Equal/maps.Equal,reflect.DeepEqual, function values (runtime.FuncForPC). - STX strings-text.md: bytes/runes (
len(s)as character count,[]rune), UTF-8 validation (utf8),string(int), string range,unicodetables. - SPR strings-processing.md:
Trim*/Cut*,SplitSeq/FieldsSeq/Lines,strings.Split/strings.Index,strings.Builder, string+=loops,bytes/bytes.Buffer,fmt.Append*/strconv.Append*,[]byte(fmt.Sprintf(.
2.3 Errors
- PAN panics.md:
panicvserror,recover,Must,panic(nil)/panicnil,debug.SetCrashOutput. - ERC errors-creating.md: wrapping (
%w/%v,fmt.Errorf, context-freereturn err/return nil, err),errors.New, sentinels (var Err) vs error types (Error() string),errors.Join,ErrUnsupported. - ERH errors-handling.md:
errors.Is/errors.AsType,err ==,err.(type),errors.As, message comparisons, timeout/cancellation sentinels (net.Error,os.ErrDeadlineExceeded,context.DeadlineExceeded), checkingerrbefore results, ignored errors (_ =,x, _ :=). - LOG logging.md:
log/slogsetup and error logging,log.Printf/log.Println, logging and returning the same error.
2.4 Concurrency
- CND concurrency-design.md: concurrency vs parallelism, spawn thresholds (goroutine per element), worker pool sizing,
runtime.NumCPU(),GOMAXPROCS. - SHR shared-state.md: data races, happens-before, race conditions, mutex vs channel, goroutine writes,
sync.Mutex/RLock, formatting under locks (fmt.Sprintf), sharedappend/maps. - SYN sync-primitives.md: typed atomics (
sync/atomic,atomic.Pointer,atomic.AddInt64/atomic.Value, goroutinen++),sync.Map,sync.Once/sync.OnceValue,sync.Cond, copiedsyncvalues. - GOR goroutine-lifecycle.md: goroutine leaks, stop plan/owner, senders blocked after early return, unbuffered result channels,
go func(),sync.WaitGroup,wg.Add/wg.Go, errgroup (g.Go,SetLimit). - CHA channels.md: notification channels and sizing (
make(chan,chan bool,chan struct{}),selectpriority, nil channels,close. - CTX context.md: passing
context.Context,defer cancel()/context.WithTimeout,ctx.Done()around blocking operations, value keys (context.WithValue,ctx.Value),context.Background()outsidemain. - CXC context-cancellation.md: cancellation causes (
ctx.Err(),<-ctx.Done(),context.Canceled/context.DeadlineExceeded/context.Cause,WithCancelCause),context.AfterFunc, background work (WithoutCancel, goroutiner.Context()),signal.Notify/signal.NotifyContext.
2.5 Standard library
- TIM time.md:
time.Durationunits/bare numbers,time.Timecomparison (==), timers in loops (time.After),time.NewTimer,time.Tick. - JSN json.md:
encoding/json,encoding/json/v2, JSON tags (omitzero,omitempty), embedded marshalers, number decoding (json.Unmarshalintomap[string]any). - SQL database-sql.md:
database/sql,sql.Open,PingContext, pool size, query arguments/prepared statements (db.Query,.Exec,QueryRow,ExecContext, SQL viafmt.Sprintf),sql.Null[T],rows.Next/rows.Err. - IOF io-and-files.md:
io.Reader/io.Writerandfs.FSparameters,filename string,os.Open,os.ReadFile,os.DirFS,os.Root,filepath.Joinwith user input. - HCL http-client-and-net.md: client timeouts/sharing/pools (
http.Get,http.Post,http.DefaultClient,http.Client,http.Transport),net/netipvsnet.IP/net.ParseIP,net.JoinHostPortvsfmt.Sprintf("%s:%d". - HSV http-server.md: handlers (
http.ResponseWriter,*http.Request,http.Handler,r.Body/r.Method),ServeMuxpatterns/HandleFunc,http.Error, server timeouts (http.ListenAndServe,http.Server),MaxBytesHandler,ResponseController,CrossOriginProtection. - RND randomness-and-ids.md:
uuid,crypto/rand,math/rand,math/rand/v2,rand.Seed.
2.6 Testing
- TBA testing-basics.md: test categories/build tags (
func TestX,//go:build integration),-race,t.Parallel,-shuffle, table-driven tests/t.Run, helpers, external_testpackages. - TST testing-state.md:
t.Cleanup,TestMain,t.Contextvs testcontext.Background(),t.Chdir/t.Setenv/t.TempDirvsos.Chdir/os.Setenv/os.MkdirTemp,testing/synctest, test time/time.Sleep,cryptotest. - TTL testing-tools.md:
httptest,testing/iotest,fstest,slogtest, fuzzing (func FuzzX). - BEN benchmarks.md:
func BenchmarkX,b.Loopvsb.N/b.ResetTimer, representative input/reuse,benchstat. - COV coverage-and-test-output.md:
-coverpkg,-cover,go build -cover/GOCOVERDIR,t.Output/t.Attr/t.ArtifactDir, testfmt.Println,go test -json.
2.7 Performance
Apply the layout, allocation, and inlining practices only to a hot path that a benchmark, profile, or trace has identified.
- PRO profiling.md: pprof (
net/http/pprof,/debug/pprof,runtime/pprof,pprof.Lookup), heap diffs, goroutine dumps,goroutineleak/block/mutex profiles (SetBlockProfileRate,SetMutexProfileFraction), labels (pprof.Do), goroutine counts (runtime/metrics). - TRC tracing.md: execution tracing (
runtime/trace,trace.Start), flight recorder (FlightRecorder), latency spikes/rare slow requests, scheduling/GC pauses. - MLY memory-layout.md: cache locality/strides (hot
[]*Tloops), false sharing (per-goroutine counters in one slice), instruction-level parallelism, field alignment,structs.HostLayout. - ALO allocations.md: escape analysis (
-gcflags, returning local pointers), caller-owned buffers, compiler-elided conversions (hotstring(b)),allocs/op,sync.Pool. - BRT build-and-runtime-tuning.md: inlining, PGO (
default.pgo),GOGC/GOMEMLIMIT/debug.SetGCPercent, container-awareGOMAXPROCS(automaxprocs,runtime.GOMAXPROCS). - CGO cgo.md: batching cgo calls (
import "C",C.),#cgodirectives (noescape,nocallback).
2.8 Project and tooling
- PKG packages-and-docs.md: project layout, package cohesion/names (
util,common), aliases (type X = Y,//go:fix inline), doc comments, missing exported doc comments,Deprecated:, examples (func ExampleX). - TOL tooling.md:
gofmt,go vet, linters (golangci-lint),tooldirectives/tools.go,go fixmodernizers, test vet checks (-vet=), CI scripts,@latest. - MOD modules-and-builds.md:
go.modhygiene/replace,godebug///go:debug, workspaces (go.work), build constraints (//go:build,// +build).
3. Apply to the task
- Writing code: satisfy every applicable practice in the routed files.
- Reviewing code: when commands are available, first run
go vet ./...,go test -race ./..., andgo fix -diff ./..., using a copy if the code must remain untouched. Check every Signals bullet in every routed file. Exclude hits covered by Exceptions. Report the rest asID | file:line | what is wrong | fix. For overlapping practices, cite the most specific ID first, then the others. Use-for problems no practice covers. Order by impact: wrong results, races, panics, leaks, hangs, then resource/performance problems, then outdated idioms/style. - Debugging: match symptoms to Signals and Why, confirm the mechanism in the code, then apply Practice.
- Modernizing code: run
go fix ./...until the diff is empty to apply the modernizers, then review the diff. Modernizers skip code shapes they cannot prove safe, so check the Signals of the routed files for the remaining outdated idioms and rewrite them by hand. Done when no Signals bullet of the routed files matches andgo vet ./...and the tests pass.
Before claiming a performance gain, measure it with a benchmark or a profile.