Reflection & Code Generation Best Practices
Choose reflection for frameworks, codegen for hot paths.
Search across all documentation pages
Choose reflection for frameworks, codegen for hot paths.
These rules turn the reflection and codegen articles in this section into reviewable habits for libraries, services, and platform teams.
pprof and benchmarks to prove reflection is a bottleneck, not assumed.Marshaler/Unmarshaler on proven hot types before adopting a new JSON generator framework.validate, json, db, custom).Tag.Lookup when key presence matters; do not rely on Get alone to detect missing keys.json names and invalid tag syntax.reflect.Type and cache field plans in sync.Map or package init.// Code generated ... DO NOT EDIT headers unless all consumers always run generators.go generate ./... produces a diff so drift is caught before merge.tools.go (build tag tools) and install that version in CI.format.Source generator output so gofmt checks pass.testdata/ inputs.-benchmem when comparing reflective JSON/ORM paths to generated alternatives.reflect.* in CPU profiles under marshal, scan, and validation handlers.go fix and go test ./....//go:fix inline on forwarding shims when renaming or moving symbols, with Deprecated: godoc.go fix -diff on large repos before applying sweeping changes.go fix twice on upgrade branches when release notes recommend synergistic passes.No.
Ban unbounded per-request reflection without measurement.
Framework initialization and admin tools are fine.
When benchmarks and SLOs prove reflective serializers or ORM scans dominate CPU or allocations.
Not before evidence exists.
Platform or service owners add the step to the standard pipeline.
Same team reviews generator version bumps.
Separate commits: one for hand-written type changes, one for go generate output only.
Yes.
Common pattern: reflect once at startup, codegen for per-request hot types.
Accept reflection cost for velocity on low-QPS paths.
Introduce sqlc/ent or slim DTOs when profiles demand it.
Deprecation tells humans to migrate.
Inline shims let go fix automate call sites when forwarding functions exist.
Yes for teaching.
Production code in the same service should follow the rules above.
Point them to Reflection Basics, then this list during first API or ORM review.
govet, errcheck, struct tag analyzers, and CI go generate diff checks.
Stack versions: This page was written for Go 1.26.x (Green Tea GC default, go fix modernizers - verify patch at build), chi (latest - verify at build), gin (latest - verify at build), echo (latest - verify at build), google.golang.org/grpc (latest - verify at build), sigs.k8s.io/controller-runtime (latest - verify at build), kubebuilder (latest - verify at build), tinygo (latest - verify board targets at build), wazero (latest - verify at build), and golangci-lint (latest - verify linter set at build).
Reviewed by Chris St. John·Last updated Jul 16, 2026