The Analogy: The Mirror in the Fitting Room
A mirror in a fitting room shows you two completely independent things about what you are wearing. It shows the cut -- this is a jacket, size 40, three pockets, one of them stitched shut -- and it shows the state, which is what is actually in those pockets right now. Go's reflect package hands you exactly those two objects: reflect.Type describes the shape, and reflect.Value holds the contents. You get them from reflect.TypeOf(x) and reflect.ValueOf(x), both of which take an any, because the whole point is that you did not know the type when you compiled.
Ordinary Go never needs this. The compiler knows every type at every call site, and that is why it is fast and why your mistakes are caught before the program runs. Reflection is for the handful of jobs where the type genuinely cannot be known in advance: a JSON decoder handed an arbitrary struct, a validator, a database row mapper, fmt.Printf itself. In each case one function must work for types that had not been written when the function was compiled.
The distinction that trips everyone is Kind versus Type. Type is the specific named type -- main.Celsius, main.Account. Kind is the underlying category from a fixed list of about twenty-six: float64, struct, slice, ptr. A defined type type Celsius float64 has Kind float64 and Type main.Celsius, so you switch on Kind to decide how to handle a value and compare Types to decide what it is.
Where the analogy stops, and it stops hard: you cannot alter a garment by touching its reflection. reflect.ValueOf(x) receives a copy of x -- the any parameter boxed it -- so nothing inside it can be modified. To change the real thing you must pass a pointer and step through it with Elem(). And there is a second wall the mirror analogy hides: reflection defeats the compiler entirely. Every mistake becomes a runtime panic, field access runs an order of magnitude slower, and no rename tool in the world will notice that a string literal in your code used to be a field name.
Syntax or Core Structure
package main
import (
"fmt"
"reflect"
)
type Celsius float64
type Account struct {
Name string
Balance int64
tags []string // unexported: visible to reflection, never settable
}
func main() {
var c Celsius = 21.5
t := reflect.TypeOf(c)
fmt.Println("type:", t, "| kind:", t.Kind(), "| named:", t.Name(), t.PkgPath())
a := Account{Name: "ada", Balance: 1000, tags: []string{"vip"}}
at, av := reflect.TypeOf(a), reflect.ValueOf(a)
fmt.Printf("%s has %d fields\n", at, at.NumField())
for i := 0; i < at.NumField(); i++ {
f := at.Field(i)
val := "<no Interface()>"
if fv := av.Field(i); fv.CanInterface() {
val = fmt.Sprint(fv.Interface())
}
fmt.Printf(" %-8s %-8s exported=%-5t canset=%-5t value=%s\n",
f.Name, f.Type, f.IsExported(), av.Field(i).CanSet(), val)
}
// ValueOf received a copy, so nothing in it can be written.
fmt.Println("copy addressable:", av.CanAddr(), "| settable:", av.Field(0).CanSet())
// Start from a pointer and step through it to reach the original.
pv := reflect.ValueOf(&a).Elem()
fmt.Println("elem addressable:", pv.CanAddr(), "| settable:", pv.Field(0).CanSet())
pv.Field(0).SetString("grace")
pv.FieldByName("Balance").SetInt(2500)
fmt.Printf("after set: %+v\n", a)
// Kind drives the switch; Type drives the identity check.
celsius := reflect.TypeOf(Celsius(0))
for _, v := range []any{7, "hi", 2.5, c, []int{1, 2}, map[string]int{"a": 1}, &a} {
rv := reflect.ValueOf(v)
fmt.Printf("%T | kind=%s | celsius=%t\n", v, rv.Kind(), rv.Type() == celsius)
}
}
Output:
type: main.Celsius | kind: float64 | named: Celsius main
main.Account has 3 fields
Name string exported=true canset=false value=ada
Balance int64 exported=true canset=false value=1000
tags []string exported=false canset=false value=<no Interface()>
copy addressable: false | settable: false
elem addressable: true | settable: true
after set: {Name:grace Balance:2500 tags:[vip]}
int | kind=int | celsius=false
string | kind=string | celsius=false
float64 | kind=float64 | celsius=false
main.Celsius | kind=float64 | celsius=true
[]int | kind=slice | celsius=false
map[string]int | kind=map | celsius=false
*main.Account | kind=ptr | celsius=false
Three lines carry the whole model. main.Celsius | kind=float64 shows Kind and Type disagreeing, exactly as designed. canset=false on Name in the first block and settable: true on the same field in the second is the difference between a copy and an Elem(). And tags proves the boundary reflection will not cross: it can be seen, described, and even printed, but CanInterface is false and CanSet will never be true.
Technical Depth: The Rules the Compiler Is No Longer Enforcing
The round trip, and what it costs
reflect.TypeOf and reflect.ValueOf take any, so calling them boxes the value into an interface -- which for anything that does not fit in a word means an allocation and a copy. Value.Interface() boxes it back on the way out. This round trip, not the field lookup, is where most of reflection's cost lives.
reflect.TypeOf(nil) returns nil, and so does TypeOf of a nil interface value, which is why every reflective entry point starts with a validity check. A reflect.Value obtained from a nil interface is the zero Value, and calling almost anything on it panics with "call of reflect.Value.Field on zero Value".
Settability has exactly three preconditions
| Question | Method | Fails when |
|---|---|---|
| Can I take its address? | CanAddr() | The Value came from ValueOf rather than through Elem() |
| Can I write to it? | CanSet() | Not addressable, or the field is unexported |
| Can I box it back out? | CanInterface() | The field is unexported (read-only flag) |
All three must hold before a Set call, and the canonical incantation is reflect.ValueOf(&x).Elem(). Note the asymmetry that catches people: an unexported field is readable through the reflection API -- you can see its name, type, and even print it -- but it can never be set and can never be handed back as an any. That is deliberate. Reflection is allowed to inspect a package's internals; it is not allowed to break its invariants.
Setters truncate; they do not check
Value.SetInt writes into a field of whatever width the field has, silently truncating. There is no overflow panic. If the source is untrusted, either pass the right bit size to strconv.ParseInt or ask Value.OverflowInt(x) first. The same applies to SetFloat and SetUint.
Walking a struct
| Call | Returns |
|---|---|
Type.NumField(), Type.Field(i) | Count and a StructField describing one field |
StructField.Name, .Type, .Tag, .IsExported() | The declaration, as data |
StructField.Anonymous | True for an embedded field |
Type.FieldByName("X") | Looks through embedded structs for a promoted field |
Value.Field(i), Value.FieldByName("X") | The corresponding contents |
Field(i) is an index into the declared fields only; FieldByName performs the promotion search that mirrors ordinary selector syntax, and returns the zero Value when nothing matches -- so check IsValid() rather than assuming. StructField.Tag is the metadata string, which is the subject of the next lesson.
Building and calling
p := reflect.New(reflect.TypeOf(Account{})) // *Account, zeroed
s := reflect.MakeSlice(reflect.TypeOf([]int{}), 0, 8)
s = reflect.Append(s, reflect.ValueOf(3))
m := reflect.MakeMap(reflect.TypeOf(map[string]int{}))
z := reflect.Zero(reflect.TypeOf("")) // the zero value of a type
out := reflect.ValueOf(strings.ToUpper).Call([]reflect.Value{reflect.ValueOf("go")})
fmt.Println(out[0].String()) // GO
Call takes and returns []reflect.Value, checks arity and assignability at runtime, and panics on a mismatch. It is how test frameworks and RPC servers dispatch to functions they have never seen.
The cost, in the shape that matters
| Operation | Rough relative cost |
|---|---|
x.Field on a concrete struct | 1 |
| Interface method call | ~2 |
Value.Field(i) after the Value exists | ~10 |
ValueOf plus FieldByName plus Interface per access | ~50 to 100 |
FieldByName is the expensive one: it compares strings on every call. Every serious reflective library therefore does the type walk once per type and caches an index -- a map[reflect.Type][]fieldInfo behind a sync.Map -- which is exactly what encoding/json does. Reflection is not slow because reflection is slow; it is slow because naive reflective code re-derives the same layout on every call.
What generics took back
Before Go 1.18, reflection was the only way to write one function over many types, and a great deal of reflective code existed purely to do Max, Contains or Map. Type parameters do that at compile time with no runtime cost and full type checking. The remaining honest uses of reflection are the ones where the set of types is open and unknown to your code: encoding and decoding, ORM-style mapping, dependency wiring, validation driven by declarations, and test harnesses.
Real World Example: Binding Config Into Any Struct
One function that fills the exported fields of any struct from string values -- the job every environment-variable and flag library does. It never mentions the concrete type, and it converts every possible panic into a returned error at the door.
package main
import (
"fmt"
"reflect"
"sort"
"strconv"
"strings"
)
type Server struct {
Host string
Port int
Debug bool
Ratio float64
Timeout int64
secret string // unexported: unreachable, and reported as unknown
}
// Bind fills the exported fields of dst, which must be a non-nil pointer to a
// struct, from values keyed by lower-cased field name.
func Bind(dst any, values map[string]string) error {
rv := reflect.ValueOf(dst)
if rv.Kind() != reflect.Pointer || rv.IsNil() {
return fmt.Errorf("bind: want non-nil pointer, got %T", dst)
}
rv = rv.Elem()
if rv.Kind() != reflect.Struct {
return fmt.Errorf("bind: want pointer to struct, got pointer to %s", rv.Kind())
}
rt := rv.Type()
index := make(map[string]int, rt.NumField())
for i := 0; i < rt.NumField(); i++ {
if rt.Field(i).IsExported() {
index[strings.ToLower(rt.Field(i).Name)] = i
}
}
var problems []string
for _, k := range sortedKeys(values) { // sorted: map order is random
i, ok := index[k]
if !ok {
problems = append(problems, fmt.Sprintf("unknown key %q", k))
continue
}
if err := setField(rv.Field(i), values[k]); err != nil {
problems = append(problems, fmt.Sprintf("%s: %v", rt.Field(i).Name, err))
}
}
if len(problems) > 0 {
return fmt.Errorf("bind: %s", strings.Join(problems, "; "))
}
return nil
}
func setField(f reflect.Value, raw string) error {
switch f.Kind() {
case reflect.String:
f.SetString(raw)
case reflect.Bool:
b, err := strconv.ParseBool(raw)
if err != nil {
return fmt.Errorf("cannot parse %q as %s", raw, f.Type())
}
f.SetBool(b)
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
// SetInt truncates silently, so the bit size given to ParseInt is
// the only thing that rejects an out-of-range value.
n, err := strconv.ParseInt(raw, 10, f.Type().Bits())
if err != nil {
return fmt.Errorf("cannot parse %q as %s", raw, f.Type())
}
f.SetInt(n)
case reflect.Float32, reflect.Float64:
x, err := strconv.ParseFloat(raw, f.Type().Bits())
if err != nil {
return fmt.Errorf("cannot parse %q as %s", raw, f.Type())
}
f.SetFloat(x)
default:
return fmt.Errorf("unsupported kind %s", f.Kind())
}
return nil
}
func sortedKeys(m map[string]string) []string {
out := make([]string, 0, len(m))
for k := range m {
out = append(out, k)
}
sort.Strings(out)
return out
}
func main() {
good := map[string]string{
"host": "10.0.0.7",
"port": "8443",
"debug": "true",
"ratio": "0.75",
"timeout": "30",
}
var s Server
if err := Bind(&s, good); err != nil {
fmt.Println("error:", err)
}
fmt.Printf("%+v\n", s)
bad := map[string]string{
"port": "eight",
"debug": "maybe",
"secret": "hunter2", // unexported field: not bindable
}
var s2 Server
fmt.Println("error:", Bind(&s2, bad))
fmt.Printf("%+v\n", s2)
fmt.Println("error:", Bind(s, good)) // a value, not a pointer
fmt.Println("error:", Bind(new(int), good)) // a pointer to the wrong thing
}
Output:
{Host:10.0.0.7 Port:8443 Debug:true Ratio:0.75 Timeout:30 secret:}
error: bind: Debug: cannot parse "maybe" as bool; Port: cannot parse "eight" as int; unknown key "secret"
{Host: Port:0 Debug:false Ratio:0 Timeout:0 secret:}
error: bind: want non-nil pointer, got main.Server
error: bind: want pointer to struct, got pointer to int
Bind never names Server, and that is the entire reason to reach for reflection. The alternative is a hand-written setter per config struct, duplicated for every service in the codebase and silently out of date whenever someone adds a field. Here a new field is bindable the moment it is declared, with no code change anywhere -- which is the same trade every serialisation library in Go makes.
The three checks at the top of Bind are the price of leaving the type system, and they are not optional. ValueOf(dst).Kind() != reflect.Pointer prevents a panic in Elem; IsNil prevents Elem returning a zero Value whose Field call panics; the second Kind check prevents NumField panicking on a *int. Each one converts a crash deep inside a library into an error the caller can read at the boundary. The rule for reflective code is to validate everything at the door and then proceed as if the compiler were still watching.
The secret field demonstrates the wall from the other side. It is skipped when the index is built, because IsExported() is false, so the key secret finds no field and is reported as unknown rather than silently ignored -- a real distinction, since silently dropping config keys is how production incidents start. Even if the index had included it, SetString would have panicked: reflection can look at unexported state but is not permitted to write it, so a package's invariants survive being reflected over.
Two production details are visible in miniature. sortedKeys exists so that the error message is byte-stable, because map iteration order is randomised and an error listing three problems in a different order every run is untestable. And the field walk runs on every call, which is the naive version: a real library computes the index map once per reflect.Type and stores it in a sync.Map, turning the per-call cost from a full type walk into one lookup. The remaining limitation is that keys must match field names -- attaching arbitrary names to fields is what struct tags are for, which is the next lesson.
Common Mistakes
- Trying to set through
reflect.ValueOf(x). Theanyparameter took a copy, soCanSetis false and theSetcall panics with "using unaddressable value". The only way in isreflect.ValueOf(&x).Elem(). - Skipping the pointer and nil checks.
Elem()on a non-pointer panics, and on a nil pointer it yields the zeroValue, whoseFieldcall panics a few lines later where the cause is much harder to see. - Switching on
Typeinstead ofKind. Aswitchover types cannot handletype Celsius float64or any other defined type a caller invents. Switch on Kind; compare Types only for identity. - Assuming
Kind() == reflect.Structmeans it is your struct. It means it is some struct. If the code depends on particular fields, check for them and return an error when they are missing. - Calling
Interface()on an unexported field. It panics. Guard withCanInterface(), and accept that some values can only be looked at, never extracted. - Reaching for reflection where generics or an interface would do. If the set of types is closed and known, a type parameter or a one-method interface gives you the same generality with compile-time checking and no cost.
- Re-deriving the layout on every call.
FieldByNamecompares strings; doing it per row of a result set is where reflective code earns its bad reputation. Cache an index perreflect.Type. - Trusting
SetIntto catch overflow. It truncates in silence. Parse with the field's own bit width, or callOverflowIntfirst. - Assuming
FieldByNamefound something. It returns the zeroValuefor a name that does not exist, and the panic surfaces later. CheckIsValid(). - Forgetting that renames are now invisible. The string
"Host"in reflective code is not a reference any tool can see, so a field rename compiles cleanly and fails at runtime. Tests are the only safety net you have left. - Using
reflect.DeepEqualin production code. It is a testing convenience: slow, untyped, and it treats a nil slice and an empty slice as different. Write the comparison you actually mean.
Best Practices
- Confine reflection to the boundary -- decoding, binding, wiring -- and convert to concrete types immediately, so the rest of the program is fully type-checked.
- Validate everything at the entry point: Kind, nil-ness, exportedness, settability. A reflective library that panics on bad input has an unfinished API.
- Switch on
Kindto decide behaviour and comparereflect.Typevalues to decide identity; they answer different questions. - Compute the field layout once per type and cache it behind a
sync.Map, exactly asencoding/jsondoes, rather than walking the struct per call. - Prefer type parameters when the set of types is closed, and reserve reflection for genuinely open sets your code cannot enumerate.
- Sort anything derived from a map before putting it in output or an error message, so results are stable and testable.
- Treat unexported fields as out of bounds: check
IsExported()when building an index, and report skipped input rather than dropping it. - Cover reflective code with tests at least as thoroughly as the rest, because the compiler is no longer checking any of the assumptions it encodes.
Practice Exercises
- Print any struct. Write
Describe(v any) stringthat reports the type name, the number of fields, and for each field its name, type, Kind and whether it is exported. Handle being passed a pointer, a non-struct andnilwithout panicking. - Zero the exported fields. Write
Reset(dst any) errorthat sets every settable field of a struct to its zero value usingreflect.Zero, and returns an error for anything that is not a non-nil pointer to a struct. Prove that an unexported field is left untouched. - Cache the layout. Extend
Bindwith async.Mapkeyed onreflect.Typeholding the name-to-index map, then confirm with a print statement that the type walk runs once for a thousand calls. - Dispatch by name. Given a struct with three methods taking a single
string, writeInvoke(v any, method, arg string) (string, error)that usesMethodByNameandCall, and returns an error rather than panicking for an unknown method or a wrong arity.