Reflection, Struct Tags, and go generate
Inspect struct tags with reflect cleanly and choose between reflect, generics, and go generate. After this, you use reflection where it fits without paying hot-path overhead.
Course content
Sign in to save your progress.
-
Bounded Concurrency and Worker Pools
-
Bound Concurrency With a Worker Pool
-
Coordinate Shared State With sync.Mutex and atomic
-
-
-
Memory, Allocations, and Benchmarking
-
Measure Speed and Allocations With go test -bench
-
Cut Allocations With Pre-Sizing and sync.Pool
-
-
-
Profiling and Diagnostics
-
Find CPU and Heap Hotspots With pprof
-
Catch Goroutine Leaks and Slow Tests Early
-
-
-
Resilience and Defensive HTTP
-
Add Retries With Backoff and Jitter
-
Protect Endpoints With Rate Limiting and Panic Recovery
-
-
-
Production Builds and Containers
-
Embed Static Assets and Version Info With embed and ldflags
-
Ship a Multi-Stage Scratch Go Container
-
-
-
Fuzzing, GC Tuning, Tracing, and Reflection
-
Fuzz Testing Parsers and Decoders With go test -fuzz
-
Escape Analysis and GC Tuning (-gcflags="-m", GOGC, GOMEMLIMIT)
-
Execution Tracing and Block/Mutex Contention Profiling
-
Reflection, Struct Tags, and go generate
-
-
Suppose your production service has a 25-field ServerConfig struct where every setting reads an environment variable like PORT or HOST and falls back to a default like "8080". Writing 25 repetitive os.Getenv + strconv.Atoi blocks is tedious and easy to mistype.
That is the exact problem Go's reflect package exists for—just like encoding/json and database/sql use it to inspect struct field names and tags at runtime. Knowing how to write safe reflection helpers at startup—and when to reach for generics or go generate instead—keeps your codebase both clean and fast.
Skip ahead
If you already inspect struct tags and populate addressable pointers with reflect.ValueOf + CanSet(), and know when generics or go generate beat runtime reflection, take the final section quiz to wrap up Go Advanced.
Experiment 1: Building a real env-var config loader with reflect
Instead of only printing tag strings, look at a complete 35-line loadFromEnv(&cfg) loader that actually populates a struct from `env:"..." default:"..."` tags, validates input types, and returns clear field-level errors:
package main
import (
"errors"
"fmt"
"os"
"reflect"
"strconv"
)
type ServerConfig struct {
Host string `env:"HOST" default:"127.0.0.1"`
Port int `env:"PORT" default:"8080"`
}
func loadFromEnv(dst any) error {
rv := reflect.ValueOf(dst)
if rv.Kind() != reflect.Pointer || rv.IsNil() || rv.Elem().Kind() != reflect.Struct {
return errors.New("dst must be a non-nil pointer to struct")
}
elem := rv.Elem()
rt := elem.Type()
for i := range rt.NumField() {
sf := rt.Field(i)
fv := elem.Field(i)
if !fv.CanSet() {
continue
}
raw := os.Getenv(sf.Tag.Get("env"))
if raw == "" {
raw = sf.Tag.Get("default")
}
if raw == "" {
continue
}
switch fv.Kind() {
case reflect.String:
fv.SetString(raw)
case reflect.Int:
n, err := strconv.Atoi(raw)
if err != nil {
return fmt.Errorf("%s: invalid int %q: %w", sf.Name, raw, err)
}
fv.SetInt(int64(n))
}
}
return nil
}
func main() {
os.Setenv("PORT", "9090")
var cfg ServerConfig
if err := loadFromEnv(&cfg); err != nil {
panic(err)
}
fmt.Printf("loaded: %+v\n", cfg)
os.Setenv("PORT", "not-a-number")
fmt.Println("bad env err:", loadFromEnv(&cfg))
}
$ go run .
loaded: {Host:127.0.0.1 Port:9090}
bad env err: Port: invalid int "not-a-number": strconv.Atoi: parsing "not-a-number": invalid syntax
Experiment 2: The three safety checks every reflect function needs
Notice why loadFromEnv guards every step before calling SetString or SetInt—because calling the wrong method on a reflect.Value does not return an error, it panics immediately:
- Pointer + non-nil + struct check: If a caller accidentally passes
loadFromEnv(cfg)by value instead of&cfg, or passes(*ServerConfig)(nil), returning an error cleanly beats crashing with a reflection panic. fv.CanSet()check: Unexported struct fields (lowercase names likesecret string) are never settable via reflection—callingfv.SetStringon them panics unless you checkCanSet()first.switch fv.Kind(): Callingfv.SetInton areflect.Stringfield panics; dispatching strictly byKind()keeps every assignment type-safe.
Experiment 3: Choosing reflect vs. generics vs. go generate
Before writing reflection code, check whether a compile-time tool fits better:
- Use generics for collection helpers, caches, queues, and worker pools—full compile-time type checks and zero reflection overhead. (Generics cannot read struct field names or struct tags.)
- Use
reflectat startup or serialization boundaries (config loaders, custom JSON/form decoders, test helpers) where inspecting struct tags is the whole job. - Use
go generatewhen you want zero runtime overhead and compile-time safety for repetitive boilerplate—like enumString()methods (stringer), typed SQL wrappers (sqlc), or gRPC/protobuf stubs:
//go:generate stringer -type=OrderStatus
type OrderStatus int
const (
StatusOpen OrderStatus = iota
StatusPaid
StatusShipped
)
Running go generate ./... generates plain, fast, readable Go code once at build time—zero runtime reflection cost.
Common mistakes
- Running reflection parsing on every HTTP request: Inspecting struct tags and building field maps on every request adds avoidable CPU and heap allocations. Run it once at startup (or cache parsed metadata per
reflect.Typein async.Map). - Passing a struct by value to a setter:
reflect.ValueOf(cfg)is non-addressable, soCanSet()isfalsefor every field. - Skipping
Kind()guards: One unexpectednilor non-struct input turns into a runtime panic instead of a clean error.
💡 Tip
Rob Pike's classic Go proverb sums it up well: "Clear is better than clever. Reflection is never clear." Keep reflection confined to small, thoroughly unit-tested boundary packages—never scatter reflect.ValueOf across business logic.
What happens if you skip this step
Using reflect carelessly on hot request paths burns CPU and invites runtime panics on invalid inputs, while avoiding reflect and go generate altogether leaves teams hand-maintaining hundreds of lines of brittle config and enum boilerplate.
In loadFromEnv(dst any), what happens if a caller passes cfg by value instead of &cfg, and why does fv.CanSet() return false on unexported struct fields?
About
Inspect struct tags with reflect cleanly and choose between reflect, generics, and go generate. After this, you use reflection where it fits without paying hot-path overhead.
- Duration
- 5 min
- Last update
- 11/27/2026
Comments
Sign in to commentNo comments yet.