Read Struct Tags With reflect in Go (and Know When to Use Codegen)
Inspect struct fields and tags at runtime with reflect.TypeOf, and decide when generics or go generate are a better fit. After this, reflection stays confined to config and serialization boundaries.
Imagine an application with a 25-field ServerConfig struct where each setting reads an environment variable like PORT or HOST and falls back to a default if unset. Writing 25 manual os.Getenv + strconv.Atoi blocks is repetitive and easy to mistype.
Go libraries solve this at startup using the reflect package to read struct tags (`env:"PORT" default:"8080"`) and populate fields automatically—while keeping reflection off hot per-request code paths.
Skip ahead
Jump straight to the real env-var config loader or the reflect vs. generics vs. go generate table.
Real example: populating a config struct from env tags
Notice the three safety guards before touching any field: confirm dst is a non-nil pointer to a struct, check fv.CanSet() (unexported fields are not settable), and wrap parsing errors with the field name:
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))
}
Output on Go 1.27:
$ 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
When to use reflect vs. generics vs. go generate
| Tool | Best fit | Drawback |
|---|---|---|
reflect |
Startup config binding, struct-tag serializers, generic test assertions | Bypasses compile-time checks; allocates on hot paths |
| Generics | Reusable containers, caches, slice/map utilities | Cannot inspect struct field names or struct tags |
go generate |
Enum stringers, SQL query wrappers (sqlc), protobufs |
Requires running go generate when schemas change |
💡 Tip
Always check rv.Kind() == reflect.Pointer and rv.Elem().Kind() == reflect.Struct before reading fields, or passing a value struct (loadFromEnv(cfg) instead of &cfg) will fail silently or panic.
Common mistakes
- Passing a non-pointer struct to a setter:
reflect.ValueOf(cfg)is not addressable, sofv.CanSet()isfalsefor every field. Always pass&cfg. - Using
reflectper HTTP request instead of once at startup: Cache parsed struct metadata once in async.Mapor use code generation on hot paths. - Writing to unexported fields with
reflect.Value: Checkfv.CanSet()before callingSet*—only exported fields of an addressable struct are settable.
⚠ Warning
Calling reflect.Value.Field or reflect.Type.NumField on a non-struct panics immediately. Guard every reflection entry point with explicit Kind() checks.
What happens if you skip this
Using reflect in hot request loops trades away compile-time safety and adds needless allocations, while avoiding reflect even for startup config loaders leads to brittle manual boilerplate.
Related course: Go Advanced.
About
Inspect struct fields and tags at runtime with reflect.TypeOf, and decide when generics or go generate are a better fit. After this, reflection stays confined to config and serialization boundaries.
- Responsible
- Jay P
- Last Update
- 11/27/2026
- Reading Time
- 3 min
Reviews
Sign in to write a reviewComments
Sign in to commentNo comments yet.