reflect: When and How
"Reflection in computing is the ability of a program to examine its own structure, particularly through types; it's a form of metaprogramming. It's also a great source of confusion." — Rob Pike, The Laws of Reflection, go.dev/blog/laws-of-reflection
Summary: reflect lets a Go program inspect and change values whose type it did not know when it was compiled. Three laws govern it (interface value to reflection object, back again, and "settable" only through a pointer); it powers encoding/json, fmt, database/sql scanners, validators and config loaders, and it costs time, type safety and clarity. Focus: reflect.TypeOf/ValueOf, Kind versus Type, Elem and pointers, settability and the exact panic texts, struct fields and tags (Tag.Get/Tag.Lookup, IsExported, CanInterface), Set* and Convert, Call and MethodByName, New/MakeSlice/MakeMap/StructOf, Implements/AssignableTo, DeepEqual and go-cmp, TypeFor, cost and caching, go generate and generics as alternatives, security, and four working mini-tools (validator, encoder, env loader, row scanner). Learning goal: Decide in one minute whether a problem needs reflection, write a safe and cached reflective helper when it does, recognise the panic you are looking at, and review someone else's reflective code without fear.
This page owns the reflect package as a Go developer uses it. It does not re-teach interfaces and type assertions (Interfaces, Type Assertions, Type Switches & any), struct and tag basics (Structs, Methods, Embedding & Struct Tags), the JSON codec built on it (JSON, XML, Struct Tags, Encoder/Decoder, Base64), generics (Generics: Type Parameters, Constraints, Where They Help), or dependency-injection design (Mocking with Interfaces, Dependency Injection for Testability, testify).
Page map
| If you are looking for | Go to |
|---|---|
| Tables you can memorise in one minute | Everything in one minute |
| Why reflection exists and what it costs | Why it exists |
| The 2011 blog post, Go 1.18 to 1.26 changes | Where it comes from |
TypeOf, ValueOf, the first law | Law 1 |
Interface(), TypeAssert, the second law | Law 2 |
Kind versus Type, named types | Kind versus Type |
Elem, reflect.Pointer, nil and the zero Value | Elem, pointers and nil |
CanSet, CanAddr, the third law, unaddressable value | Settability |
NumField, Field, FieldByName, VisibleFields | Walking a struct |
StructTag, Tag.Get, Tag.Lookup | Struct tags |
IsExported, CanInterface, unexported fields | Exported and unexported |
SetString, SetInt, Set, Convert, SetZero | Reading and setting |
MakeSlice, MakeMap, MapRange, Append, Index | Slices and maps |
Call, MethodByName, variadics, MakeFunc | Calling functions |
reflect.New, SliceOf, MapOf, StructOf, FuncOf | Making types and values |
Implements, AssignableTo, ConvertibleTo, Comparable | Type relations |
DeepEqual, NaN, nil versus empty, unexported | DeepEqual |
go-cmp, cmpopts, cmp.Diff | go-cmp |
TypeFor, Seq, Fields, version table | Versions |
allocations, caching reflect.Type lookups | Performance |
generics, interfaces, go generate instead | Alternatives |
encoding/json, fmt, sqlx, pgx, validators, DI containers | In the wild |
| Reflecting over untrusted type names | Security |
unsafe, reflectlite, what go vet cannot check | unsafe, reflectlite and vet |
| Every panic text | Mechanics |
| A validator, encoder, env loader, row scanner | Solving the classic problems |
| Reflect or not | Choosing |
| Monolith to distributed system | In architecture |
| Reproduce the outputs | Lab |
| Wrong beliefs, cheat sheet, every term | Misconceptions, Cheat sheet, Glossary |
Everything in one minute
The three laws (from the Go blog).
| Law | In plain words | Code | Failure when broken |
|---|---|---|---|
| 1. Interface value to reflection object | Hand any value to TypeOf/ValueOf and you get its type and its value | reflect.TypeOf(x), reflect.ValueOf(x) | TypeOf(nil) is nil; ValueOf(nil) is an invalid Value |
| 2. Reflection object to interface value | v.Interface() gives the value back as any; assert it to use it | v.Interface().(float64) | Panic if the field is unexported; ok == false for a wrong type |
| 3. To modify a reflection object, it must be settable | You can change only the real variable, so go through a pointer and Elem() | reflect.ValueOf(&x).Elem().SetFloat(7.1) | panic: reflect: reflect.Value.SetFloat using unaddressable value |
The two questions every Value answers.
| Question | Method | ValueOf(x) | ValueOf(&x).Elem() | Field of an unexported name |
|---|---|---|---|---|
| Is it a real variable I could take the address of? | CanAddr() | false | true | depends on the parent |
| May I assign to it? | CanSet() | false | true | false |
May I call Interface() on it? | CanInterface() | true | true | false |
The kinds you meet every day.
Kind | Typical Type | Getter | Setter |
|---|---|---|---|
Bool | bool | Bool() | SetBool |
Int, Int8 ... Int64 | int, time.Duration | Int() | SetInt |
Uint ... Uint64, Uintptr | uint8, uint64 | Uint() | SetUint |
Float32, Float64 | float64, Celsius | Float() | SetFloat |
String | string, ID | String() | SetString |
Slice, Array | []byte, [4]int | Len(), Index(i) | Set, SetLen, Index(i).Set* |
Map | map[string]int | MapKeys(), MapIndex, MapRange | SetMapIndex |
Struct | time.Time, User | NumField(), Field(i) | Field(i).Set* |
Pointer | *User | Elem() | Set |
Interface | error, any | Elem() | Set |
Func | func(int) string | Call | Set |
Chan | chan int | Send, Recv | none |
Do I need it?
| Situation | Reflect? | Better first try |
|---|---|---|
| Many types, same algorithm, known at compile time | no | generics or an interface |
| A fixed handful of types | no | a switch v := x.(type) |
| One type, many call sites | no | write the code, or go generate it |
| Shape known only at run time (codec, ORM, validator, config) | yes | one small cached package |
| Names come from untrusted input | no | an explicit allow-list map |
Why it exists
A Go program is statically typed: the compiler knows every type. Some programs have to work with types they were never compiled against: fmt.Println prints any value, encoding/json encodes any struct, a database scanner fills any row type, a validator checks any form. An any hides the type; reflection opens the box. The price is that the compiler stops helping, because type checking moves to run time: errors become panics, speed drops, and the code is harder to read.
| Choice | Strength | Weakness |
|---|---|---|
Static code (switch, interface, generics) | Checked at build, fast, readable | You list every type up front |
| Reflection | One function serves types it has never seen | Run-time panics, from about 5 to about 100 times slower than a direct field write in this chapter's benchmark, hard to read |
Code generation (go generate) | Static speed with no hand-written repetition | Build step, generated files in review |
| Struct tags plus reflection | Metadata lives next to the field | Tags are untyped strings; typos are silent |
An everyday picture. A hotel master key. Ordinary code uses the key to your own room, which is safe and fast. Reflection is the master key: it opens every door, including rooms you were never meant to enter, and it takes longer because you must look up which door you are standing at. A hotel needs one now and then; it does not hand one to every guest.
Three common misunderstandings, up front
- "Reflection lets me change anything." It does not: unexported fields and values copied into an interface cannot be set, and the runtime panics instead of silently ignoring the attempt.
- "
KindandTypeare the same." ACelsiushasKindfloat64butTypeCelsius; code that asserts onTypeand code that switches onKindbehave differently. - "Reflection is just slow." The reflect call itself is cheap when it is cached; what hurts is looking things up by name and parsing tags on every request, and the allocations of boxing values back into
any.
Where it comes from
Go's reflection model is described in a go.dev blog post by Rob Pike, The Laws of Reflection (2011), which says that "Reflection in computing is the ability of a program to examine its own structure, particularly through types". It states three laws: "Reflection goes from interface value to reflection object", "Reflection goes from reflection object to interface value" and "To modify a reflection object, the value must be settable". The model rests on the fact that an interface variable holds a pair (value, concrete type), which the blog post explains before it introduces reflect.
The package has grown conservatively. Go 1.17 added VisibleFields and StructField.IsExported; Go 1.18 renamed Ptr and PtrTo to Pointer and PointerTo (the old names remain); Go 1.20 added SetZero, Comparable and Equal; Go 1.21 stopped forcing the argument of ValueOf onto the heap and added Value.Clear; Go 1.22 added reflect.TypeFor[T]() and deprecated PtrTo; Go 1.23 added Value.Seq/Seq2; Go 1.25 added reflect.TypeAssert; Go 1.26 added iterator methods Type.Fields, Type.Methods, Type.Ins, Type.Outs, Value.Fields, Value.Methods. All of this is taken from the release notes saved for this chapter (see References); the Go 1.17, 1.18 and 1.20 items come from those release notes too. The Go FAQ and Effective Go say little about reflection beyond pointing to the blog post, which is itself a hint: the language wants reflection to be rare.
The concept catalogue
Law 1: TypeOf and ValueOf Must-know
In plain words: reflect.TypeOf(x) returns a reflect.Type that describes what x is; reflect.ValueOf(x) returns a reflect.Value that holds what x contains. Both start from an any, so passing a value converts it to an interface first.
Common misunderstanding: "ValueOf(x) gives me x." It gives a copy wrapped in a Value. Changing the Value is impossible (it is not addressable) and would not change x if it were.
Definition: func TypeOf(i any) Type and func ValueOf(i any) Value. TypeOf(nil) returns a nil Type; ValueOf(nil) returns the zero Value, whose IsValid() is false, and most methods on it panic. Type is an interface (many methods, only a few valid per kind); Value is a struct.
Law 1: from an interface to the two reflection objects
1 var x float64 = 3.4 x is a float64 variable
2 any(x) interface holds (type=float64, value=3.4 copy)
3 t := reflect.TypeOf(x) t.String() == "float64", t.Kind() == reflect.Float64
4 v := reflect.ValueOf(x) v.Float() == 3.4, v.CanSet() == false
5 reflect.TypeOf(nil) nil (no dynamic type)
6 reflect.ValueOf(nil).IsValid() false (the zero Value)Real scenario: a logging helper prints type=laws.Celsius kind=float64 value=21.5 for whatever it is handed; a generic "describe this payload" admin endpoint does the same for decoded JSON; a test helper calls TypeOf(nil) for an untyped nil argument and must not dereference the result.
The first snippet defines every demonstration used on this page, with the exact panic texts of the Go version used here (1.27.4); the tests assert each text.
// Package laws demonstrates the three laws of reflection, Kind versus Type,
// and settability, with the exact panic texts the runtime produces.
package laws
import (
"fmt"
"reflect"
)
// Celsius is a named type whose Kind is Float64 but whose Type is not float64.
type Celsius float64
// Describe returns the Type, the Kind and the printed value of any value.
// Law 1: interface value -> reflection object.
func Describe(x any) string {
t := reflect.TypeOf(x)
v := reflect.ValueOf(x)
if t == nil {
return "nil interface: TypeOf returned nil"
}
return fmt.Sprintf("type=%s kind=%s value=%v", t, t.Kind(), v)
}
// RoundTrip is law 2: reflection object -> interface value, with an assertion.
func RoundTrip(x any) (float64, bool) {
v := reflect.ValueOf(x)
f, ok := v.Interface().(float64)
return f, ok
}
// SetThroughValue shows law 3. It returns what CanSet reports for the Value
// of x itself and for the Value reached through a pointer, then sets 7.1.
func SetThroughValue() (direct, viaPointer bool, result float64) {
x := 3.4
v := reflect.ValueOf(x)
direct = v.CanSet()
p := reflect.ValueOf(&x).Elem()
viaPointer = p.CanSet()
p.SetFloat(7.1)
return direct, viaPointer, x
}
// PanicText runs f and returns the text of the panic it raised, or "".
func PanicText(f func()) (msg string) {
defer func() {
if r := recover(); r != nil {
msg = fmt.Sprint(r)
}
}()
f()
return ""
}
// UnaddressableSet triggers the classic panic by setting a non-pointer Value.
func UnaddressableSet() string {
return PanicText(func() {
reflect.ValueOf("hello").SetString("x")
})
}
// UnexportedSet triggers the panic for a field reached through unexported name.
func UnexportedSet() string {
type box struct{ secret int }
b := box{}
return PanicText(func() {
reflect.ValueOf(&b).Elem().Field(0).SetInt(1)
})
}
// WrongKind triggers the panic for calling a setter of the wrong Kind.
func WrongKind() string {
n := 1
return PanicText(func() {
reflect.ValueOf(&n).Elem().SetString("x")
})
}
// ElemOnStruct triggers the panic for Elem on a Kind that has no element.
func ElemOnStruct() string {
return PanicText(func() {
reflect.ValueOf(struct{}{}).Elem()
})
}
// NilInterface shows the zero Value: TypeOf(nil) is nil, ValueOf(nil) is invalid.
func NilInterface() (typeIsNil bool, valid bool) {
var x any
return reflect.TypeOf(x) == nil, reflect.ValueOf(x).IsValid()
}
// KindVsType returns Type and Kind strings for a named type and its underlying type.
func KindVsType() (named, underlying string) {
c := Celsius(21.5)
return reflect.TypeOf(c).String() + "/" + reflect.TypeOf(c).Kind().String(),
reflect.TypeOf(float64(c)).String() + "/" + reflect.TypeOf(float64(c)).Kind().String()
}
// PointerKind reports the Kind of a pointer and of what it points to.
func PointerKind() (string, string) {
n := 1
t := reflect.TypeOf(&n)
return t.Kind().String(), t.Elem().Kind().String()
}
// TypeForMatches reports that TypeFor[T]() equals TypeOf((*T)(nil)).Elem().
func TypeForMatches() bool {
return reflect.TypeFor[Celsius]() == reflect.TypeOf((*Celsius)(nil)).Elem()
}| Call | Result for Celsius(21.5) | Note |
|---|---|---|
reflect.TypeOf(x).String() | laws.Celsius | Package-qualified |
reflect.TypeOf(x).Name() | Celsius | Empty for unnamed types such as []int |
reflect.TypeOf(x).PkgPath() | academy/reflect/laws | Empty for built-in types |
reflect.TypeOf(x).Kind() | float64 | The underlying category |
reflect.ValueOf(x).Float() | 21.5 | Getter chosen by Kind |
reflect.TypeOf(nil) | nil | Guard before calling methods |
Law 2: Interface() and TypeAssert Must-know
In plain words: v.Interface() turns a Value back into an ordinary any. After that you use a type assertion or a type switch, as with any interface value. Interface() and ValueOf are inverses.
Common misunderstanding: "Interface() returns a value of the right static type." It returns any; the compiler still does not know the type, so you assert to a concrete type you already expect (v.Interface().(float64)) or switch on it.
Definition: func (v Value) Interface() any. It panics when the Value was obtained by accessing unexported struct fields (text: reflect.Value.Interface: cannot return value obtained from unexported field or method). Go 1.25 added func TypeAssert[T any](v Value) (T, bool), semantically v.Interface().(T) but without the extra allocation. Value.CanInterface() reports whether Interface() is safe.
Law 2: from a Value back to a typed value
1 v := reflect.ValueOf(Celsius(21.5))
2 v.Interface() any holding Celsius(21.5)
3 v.Interface().(float64) ok == false: the dynamic type is Celsius
4 v.Interface().(Celsius) 21.5, ok == true
5 reflect.TypeAssert[Celsius](v) 21.5, true (Go 1.25, no allocation)
6 v.Field(0).Interface() (unexported) panic: cannot return value obtained from unexported field or methodReal scenario: a generic printer walks a map and calls Interface() on each element to hand it to fmt; a mapper writes row[i] = field.Interface() to build a []any for database/sql; a decoder guards with CanInterface() so a private field never panics a request.
| Need | Call | Allocates? | Panics when |
|---|---|---|---|
Back to any | v.Interface() | boxing a non-pointer value allocates | unexported field |
| Back to a concrete type | v.Interface().(T) | same | wrong type (single-value form) |
| Back to a concrete type without boxing | reflect.TypeAssert[T](v) | no | never; returns ok |
| Primitive without boxing | v.Int(), v.String(), v.Float() | no | wrong Kind |
| Check first | v.CanInterface() | no | never |
Kind versus Type Must-know
In plain words: The Type is the exact name of the type (main.Celsius). The Kind is the family it belongs to (float64, struct, ptr, slice). Code that must handle every integer-like type switches on Kind; code that must recognise one particular type compares Type.
Common misunderstanding: "t == reflect.TypeOf(0) tells me it is an int." It tells you it is exactly int; a type Count int or a time.Duration has Kind Int64 or Int but a different Type, and == is false.
Definition: Kind is a uint enumeration (Invalid, Bool, Int ... Complex128, Array, Chan, Func, Interface, Map, Pointer, Slice, String, Struct, UnsafePointer). Type values are comparable with ==, so they work as map keys; that is how every cache on this page is keyed. Kind.String() for pointers is ptr, not pointer.
Type vs Kind
1 type Celsius float64
2 reflect.TypeOf(Celsius(1)).String() -> "laws.Celsius"
3 reflect.TypeOf(Celsius(1)).Kind() -> float64
4 reflect.TypeOf(float64(1)) == reflect.TypeOf(Celsius(1)) -> false
5 reflect.TypeOf(time.Second).Kind() -> int64
6 reflect.TypeOf(&n).Kind(), reflect.TypeOf(&n).Elem().Kind() -> ptr, intReal scenario: a config loader accepts time.Duration fields by comparing Type first (a Duration is an Int64 kind that must be parsed as "5s", not as digits) and then falls back to Kind; a JSON encoder treats []byte (a Slice of Uint8) differently from []int; a validator's min rule works for any integer Kind, including named types.
| Question | Compare Type | Switch on Kind |
|---|---|---|
Is it exactly time.Time? | t == reflect.TypeFor[time.Time]() | no, Kind is struct |
| Is it any integer, named or not? | no | case reflect.Int, reflect.Int8, ... |
Is it a []byte? | t == reflect.TypeFor[[]byte]() | Slice plus t.Elem().Kind() == Uint8 |
Is it an error? | t.Implements(errorType) | Interface or any kind with the method |
package laws
import "testing"
func TestDescribe(t *testing.T) {
got := Describe(Celsius(21.5))
want := "type=laws.Celsius kind=float64 value=21.5"
if got != want {
t.Fatalf("got %q want %q", got, want)
}
if got := Describe(nil); got != "nil interface: TypeOf returned nil" {
t.Fatalf("got %q", got)
}
}
func TestRoundTrip(t *testing.T) {
if f, ok := RoundTrip(3.4); !ok || f != 3.4 {
t.Fatalf("got %v %v", f, ok)
}
if _, ok := RoundTrip(Celsius(3.4)); ok {
t.Fatal("named type must not assert to float64")
}
}
func TestSettability(t *testing.T) {
direct, via, res := SetThroughValue()
if direct || !via || res != 7.1 {
t.Fatalf("direct=%v via=%v res=%v", direct, via, res)
}
}
func TestPanicTexts(t *testing.T) {
cases := map[string]struct{ got, want string }{
"unaddressable": {UnaddressableSet(), "reflect: reflect.Value.SetString using unaddressable value"},
"unexported": {UnexportedSet(), "reflect: reflect.Value.SetInt using value obtained using unexported field"},
"wrong kind": {WrongKind(), "reflect: call of reflect.Value.SetString on int Value"},
"elem": {ElemOnStruct(), "reflect: call of reflect.Value.Elem on struct Value"},
}
for name, c := range cases {
if c.got != c.want {
t.Errorf("%s: got %q want %q", name, c.got, c.want)
}
}
}
func TestNilAndKinds(t *testing.T) {
if isNil, valid := NilInterface(); !isNil || valid {
t.Fatalf("isNil=%v valid=%v", isNil, valid)
}
n, u := KindVsType()
if n != "laws.Celsius/float64" || u != "float64/float64" {
t.Fatalf("%s %s", n, u)
}
k, e := PointerKind()
if k != "ptr" || e != "int" {
t.Fatalf("%s %s", k, e)
}
if !TypeForMatches() {
t.Fatal("TypeFor mismatch")
}
}Elem, pointers and nil Must-know
In plain words: Elem() follows a pointer (or unwraps an interface) to what it points at. A Type of kind Pointer has an element type; a Value of kind Pointer has an element value. The reflective version of *p is v.Elem().
Common misunderstanding: "If I have a *User, NumField works on it." reflect.TypeOf(&u).NumField() panics: reflect: NumField of non-struct type *main.User. Walk the Elem() first, and handle nil pointers.
Definition: Value.Elem() panics unless the kind is Interface or Pointer, and returns the zero Value for a nil pointer or nil interface. reflect.Indirect(v) is Elem() for pointers and the identity for everything else. Type.Elem() also works for Array, Chan, Map and Slice (their element type); Type.Key() gives the map key type. reflect.Pointer replaced reflect.Ptr in Go 1.18, and reflect.PointerTo(t) replaced PtrTo in the same release (the old name was deprecated in Go 1.22).
Dereferencing safely
1 v := reflect.ValueOf(p) p is *User
2 v.Kind() == reflect.Pointer true
3 v.IsNil() check before Elem
4 e := v.Elem() the User variable itself, CanAddr() true
5 e.Kind() == reflect.Struct now NumField, Field(i) are legal
6 reflect.ValueOf((*User)(nil)).Elem() zero Value; e.Field(0) panics "call of reflect.Value.Field on zero Value"Real scenario: a form binder accepts both User and *User; a printer follows a chain **T in a loop until the kind is not a pointer; an ORM builds []*Row and []Row results with the same code by calling Indirect on each element type.
| Value | Kind() | Elem() gives | Guard |
|---|---|---|---|
&u where u is User | Pointer | the User variable | IsNil() |
(*User)(nil) | Pointer | zero Value | check IsValid() after Elem() |
any(7) seen as a struct field of type any | Interface | the int 7 | IsNil() first |
[]int{1} (a Type) | Slice | int (type's Elem()) | none |
map[string]int (a Type) | Map | int; Key() is string | none |
Settability: CanSet, CanAddr and unaddressable value Must-know
In plain words: A Value is settable when assigning to it would change a real variable. A Value made from a plain value is a private copy, so setting it would change nothing and Go refuses with a panic. A Value reached through a pointer is the real variable, so it can be set.
Common misunderstanding: "reflect.ValueOf(x).SetInt(5) should update x." The value was copied into an interface before reflection saw it. The runtime text is panic: reflect: reflect.Value.SetString using unaddressable value (for SetString; the method name changes). The fix is reflect.ValueOf(&x).Elem().
Definition: CanAddr() is true for values reached through a pointer's Elem(), a field of an addressable struct, or an element of a slice (slices are always addressable) or an addressable array. CanSet() is CanAddr() and "not obtained via an unexported struct field". Map elements and values returned by function calls are never addressable. All Set* methods panic when CanSet() is false; Interface()-obtained copies stay unsettable.
Law 3: settability
1 x := 3.4
2 v := reflect.ValueOf(x) CanSet() false: v holds a copy
3 v.SetFloat(7.1) panic: reflect: reflect.Value.SetFloat using unaddressable value
4 p := reflect.ValueOf(&x) p is a pointer Value; p.CanSet() false (the pointer itself is a copy)
5 e := p.Elem() e is x itself, CanAddr() true, CanSet() true
6 e.SetFloat(7.1) x == 7.1Real scenario: a YAML or env loader receives cfg any and must write into the caller's struct (pointer required); a test helper that "zeroes every field" fails on a struct passed by value; a patcher skips unexported fields by checking CanSet() rather than catching panics.
| What you hold | CanAddr() | CanSet() | Why |
|---|---|---|---|
ValueOf(x) | false | false | a copy sits in the interface |
ValueOf(&x).Elem() | true | true | the variable itself |
ValueOf(&s).Elem().Field(i), exported | true | true | field of an addressable struct |
| same, unexported field | true | false | set denied by export rules |
ValueOf(s).Field(i) | false | false | struct passed by value |
ValueOf(slice).Index(i) | true | true (if exported element) | slices are backed by an array |
ValueOf(arr).Index(i) | false | false | array copied into the interface |
v.MapIndex(k) | false | false | map elements are not addressable; use SetMapIndex |
The error texts you will meet while working on settability, all produced by the code above and asserted in its test:
| Mistake | Panic text (Go 1.27.4) |
|---|---|
| Set on a copy | reflect: reflect.Value.SetString using unaddressable value |
| Set an unexported field | reflect: reflect.Value.SetInt using value obtained using unexported field |
| Wrong setter for the kind | reflect: call of reflect.Value.SetString on int Value |
Elem on a struct | reflect: call of reflect.Value.Elem on struct Value |
| Set a value of another type | reflect.Set: value of type string is not assignable to type int |
Use of the zero Value | reflect: call of reflect.Value.Type on zero Value |
Walking a struct: NumField, Field, FieldByName Must-know
In plain words: To look at every field of a struct you ask its Type how many fields it has, then fetch the field description (StructField: name, type, tag) and the field value for each index.
Common misunderstanding: "Field(i) on the value and on the type are the same thing." Type.Field(i) returns a StructField (a description: Name, Type, Tag, Index, Anonymous, PkgPath); Value.Field(i) returns a Value (the data). You usually need both.
Definition: Type.NumField(), Type.Field(i) StructField, Type.FieldByName(name) (StructField, bool), Value.NumField(), Value.Field(i) Value, Value.FieldByName(name) Value (zero Value when absent), Value.FieldByIndex([]int) for nested or promoted fields, reflect.VisibleFields(t) for all fields reachable by FieldByName, including those promoted from embedded structs. Embedded structs show up as one field with Anonymous == true; their fields are promoted through Index paths of length two or more. Go 1.26 added Type.Fields() and Value.Fields() iterators.
Walking a struct
1 rt := reflect.TypeFor[User]() rt.Kind() == reflect.Struct
2 for i := 0; i < rt.NumField(); i++ { 7 direct fields for fields.User
3 sf := rt.Field(i) sf.Name, sf.Type, sf.Tag, sf.IsExported()
4 fv := rv.Field(i) fv.CanSet(), fv.CanInterface()
5 }
6 rt.FieldByName("City") found through the embedded Address: Index [5 0]
7 reflect.VisibleFields(rt) every field FieldByName can reach, with Index pathsReal scenario: encoding/json computes the list of fields of a type once and caches it; an audit-log helper prints every exported field of a request struct; a form decoder maps name="email" to the field tagged form:"email".
// Package fields walks a struct with reflection: names, types, tags,
// exported checks, embedded fields and the CanInterface/CanSet difference.
package fields
import (
"fmt"
"reflect"
"strings"
)
// Address is nested to show recursion and embedding.
type Address struct {
City string `json:"city" db:"city"`
Zip string `json:"zip,omitempty"`
}
// User mixes exported, unexported, tagged and embedded fields.
type User struct {
ID int64 `json:"id" db:"id" validate:"required"`
Name string `json:"name" db:"name" validate:"required,min=2"`
Email string `json:"email,omitempty" db:"email"`
secret string
Skipped string `json:"-"`
Address // embedded: promoted fields City and Zip
Tags []string `json:"tags"`
}
// Info is one row of the walk.
type Info struct {
Name string
Type string
Kind string
Tag string
Exported bool
Anonymous bool
CanSet bool
CanIface bool
}
// Walk lists the direct fields of v (a struct or a pointer to a struct).
func Walk(v any) []Info {
rv := reflect.ValueOf(v)
if rv.Kind() == reflect.Pointer {
rv = rv.Elem()
}
if rv.Kind() != reflect.Struct {
return nil
}
rt := rv.Type()
out := make([]Info, 0, rt.NumField())
for i := 0; i < rt.NumField(); i++ {
sf := rt.Field(i)
fv := rv.Field(i)
out = append(out, Info{
Name: sf.Name,
Type: sf.Type.String(),
Kind: sf.Type.Kind().String(),
Tag: string(sf.Tag),
Exported: sf.IsExported(),
Anonymous: sf.Anonymous,
CanSet: fv.CanSet(),
CanIface: fv.CanInterface(),
})
}
return out
}
// TagLookup returns the value of key in the tag of the named field and
// whether the key was present (Lookup separates "" from "absent").
func TagLookup(v any, field, key string) (string, bool) {
t := reflect.TypeOf(v)
if t.Kind() == reflect.Pointer {
t = t.Elem()
}
sf, ok := t.FieldByName(field)
if !ok {
return "", false
}
return sf.Tag.Lookup(key)
}
// Flatten returns "path=value" lines for every exported leaf, descending into
// nested and embedded structs. It never calls Interface on unexported fields.
func Flatten(v any) []string {
var out []string
flatten(reflect.ValueOf(v), "", &out)
return out
}
func flatten(v reflect.Value, prefix string, out *[]string) {
switch v.Kind() {
case reflect.Pointer:
if v.IsNil() {
*out = append(*out, prefix+"=<nil>")
return
}
flatten(v.Elem(), prefix, out)
case reflect.Struct:
t := v.Type()
for i := 0; i < t.NumField(); i++ {
sf := t.Field(i)
if !sf.IsExported() {
continue
}
name := sf.Name
if sf.Anonymous {
name = ""
}
p := prefix
if name != "" {
if p != "" {
p += "."
}
p += name
}
flatten(v.Field(i), p, out)
}
case reflect.Slice:
parts := make([]string, v.Len())
for i := range parts {
parts[i] = fmt.Sprint(v.Index(i).Interface())
}
*out = append(*out, prefix+"=["+strings.Join(parts, ",")+"]")
default:
*out = append(*out, fmt.Sprintf("%s=%v", prefix, v.Interface()))
}
}
// SetByName sets an exported field by name from a string-typed value, the way
// form binders and config loaders do. It returns an error instead of panicking.
func SetByName(dst any, field string, value int64) error {
rv := reflect.ValueOf(dst)
if rv.Kind() != reflect.Pointer || rv.IsNil() {
return fmt.Errorf("fields: dst must be a non-nil pointer, got %T", dst)
}
f := rv.Elem().FieldByName(field)
switch {
case !f.IsValid():
return fmt.Errorf("fields: no field %q", field)
case !f.CanSet():
return fmt.Errorf("fields: field %q is not settable", field)
case !f.CanInt():
return fmt.Errorf("fields: field %q has kind %s, not an integer", field, f.Kind())
case f.OverflowInt(value):
return fmt.Errorf("fields: %d overflows %s", value, f.Type())
}
f.SetInt(value)
return nil
}| Method | On | Returns | Panics when |
|---|---|---|---|
NumField() | Type, Value | field count | not a struct (reflect: NumField of non-struct type int) |
Field(i) | Type | StructField | i out of range |
Field(i) | Value | Value | not a struct (reflect: call of reflect.Value.Field on int Value) |
FieldByName(n) | Type | (StructField, bool) | not a struct |
FieldByName(n) | Value | Value, zero if absent | not a struct |
FieldByIndex(path) | both | nested field | a nil embedded pointer on the path (use FieldByIndexErr) |
VisibleFields(t) | package | all reachable fields | t is not a struct |
Struct tags: StructTag, Tag.Get and Tag.Lookup Must-know
In plain words: A tag is a string after a field (`json:"id" db:"id"`). Reflection reads it; the compiler does not look inside. Tag.Get("json") gives the value for the key json.
Common misunderstanding: "Tag.Get returning "" means the key is missing." It also returns "" for a present key with an empty value (`x:""`). Use Tag.Lookup, which returns (value, ok), whenever "absent" and "empty" mean different things.
Definition: type StructTag string. By convention a tag is a space-separated list of key:"value" pairs; each key is a non-empty string of non-control characters other than space, quote and colon; each value is quoted using Go string literal syntax. Get and Lookup parse on every call, so they are cheap but not free (see Performance). Tags are untyped: a typo like json:name (no quotes) is silently ignored by reflect, but go vet reports it.
Tag parsing, field by field
1 `json:"email,omitempty" db:"email" validate:"required,min=2"`
2 sf.Tag.Get("json") "email,omitempty" (library splits at the comma)
3 sf.Tag.Get("db") "email"
4 sf.Tag.Lookup("xml") "", false
5 `x:""` then Lookup("x") "", true (present but empty)
6 `json:name` go vet: struct field tag `json:name` not compatible with reflect.StructTag.Get: bad syntax for struct tag valueReal scenario: json, xml, yaml, db (sqlx), gorm, validate (go-playground/validator), env (envconfig) and form tags are all read this way; a library defines its own mini-language after the comma (omitempty, required, min=3) and splits it with strings.Cut or strings.Split.
| Convention | Meaning | Library |
|---|---|---|
json:"name,omitempty" | key, option | encoding/json |
json:"-" | skip | encoding/json, most others |
db:"column" | column name | sqlx, pgx (RowToStructByName) |
validate:"required,min=2" | rules | go-playground/validator and the mini validator below |
env:"PORT" default:"8080" | variable and default | envconfig-style loaders |
xml:"id,attr" | XML attribute | encoding/xml |
The tag grammar and the vet check are in Structs, Methods, Embedding & Struct Tags; this page uses them as reflection input.
Exported and unexported: IsExported, CanInterface Important
In plain words: A field whose name starts with a lower-case letter belongs to its package. Reflection can see that it exists, can read its type and tag, but cannot hand out its value or change it. Go keeps the package boundary even for reflection.
Common misunderstanding: "reflect bypasses visibility." It does not: Interface() and every Set* panic for unexported fields. The escape hatch is unsafe (see unsafe, reflectlite and vet), and using it is a design smell.
Definition: StructField.IsExported() is true when PkgPath is empty. Value.CanInterface() is false for a value reached through an unexported field. Reading with Int(), String(), Bool(), Float() and Len() still works on unexported fields; copying out as any (Interface()) and writing do not. reflect.DeepEqual compares unexported fields (it has package-internal access); go-cmp refuses them unless told to ignore them.
Unexported field behaviour (struct { secret int; Public int })
1 sf := rt.Field(0) sf.Name == "secret", sf.IsExported() == false, sf.PkgPath != ""
2 rv.Field(0).Int() works: reading a kind-specific getter is allowed
3 rv.Field(0).Interface() panic: reflect.Value.Interface: cannot return value obtained from unexported field or method
4 rv.Field(0).CanSet() false, even through a pointer
5 rv.Field(0).SetInt(1) panic: reflect: reflect.Value.SetInt using value obtained using unexported field
6 fmt.Println(s) fmt prints it via reflection internals without Interface()Real scenario: a generic Flatten helper skips !sf.IsExported() so that private state never leaks into logs; a test helper that dumps a struct uses fmt.Sprintf("%+v") because fmt has internal access to unexported fields while your code does not; a library refuses to marshal a struct whose only fields are lower-case and returns {}.
| Operation on an unexported field | Allowed? |
|---|---|
Read Type, Name, Tag, Index | yes |
Int(), String(), Len(), IsZero() | yes |
Interface() | no, panics |
Set*, Set | no, panics |
Call on a func field | no, panics |
Addr() then Interface() | no, still unexported |
Reading and setting values: Set*, Convert, SetZero Must-know
In plain words: Getters (Int, String, Bool, Float) read a primitive; setters (SetInt, SetString, SetBool, SetFloat) write one; Set(x) assigns any Value of an assignable type; Convert(t) returns the value converted to another type, as T(x) would in source.
Common misunderstanding: "SetInt works on any number field." SetInt works on kinds Int...Int64 only; use SetUint for unsigned and SetFloat for floats. A wrong kind panics: reflect: call of reflect.Value.SetString on int Value. Overflow is silent for SetInt (it truncates to the field width), so check OverflowInt first.
Definition: CanInt(), CanUint(), CanFloat(), CanComplex() report whether the matching getter is legal. OverflowInt(x), OverflowUint(x), OverflowFloat(x) report whether x fits the kind. Set(x) panics unless x is assignable to v.Type() (reflect.Set: value of type string is not assignable to type int). Convert(t) panics unless ConvertibleTo(t); CanConvert(t) is the safe check and Convert follows Go's conversion rules, including float to int truncation and int to string producing a rune. SetZero() (Go 1.20) resets to the zero value; IsZero() tests for it.
Setting safely: parse, check, set
1 f := rv.Elem().FieldByName("Timeout") f.IsValid() must be true
2 f.CanSet() false for unexported or copies
3 f.Type() == reflect.TypeFor[time.Duration]() special-case before looking at Kind
4 n, err := strconv.ParseInt(raw, 10, f.Type().Bits()) fits the field width
5 f.OverflowInt(n) defensive: reject, do not truncate
6 f.SetInt(n)Real scenario: an env loader parses "5s" for a time.Duration field and "8080" for an int field and writes both with the right setter; a feature-flag decoder uses SetBool; a migration tool zeroes every field tagged secret with SetZero before logging.
| Goal | Call | Panics when |
|---|---|---|
| Write an integer field | SetInt(n) | not a settable signed integer kind |
| Write an unsigned field | SetUint(n) | wrong kind or not settable |
| Write a float field | SetFloat(f) | wrong kind |
| Write any assignable value | Set(reflect.ValueOf(x)) | x not assignable, or not settable |
Same as T(x) | v.Convert(t) | not convertible (reflect.Value.Convert: value of type string cannot be converted to type []int) |
| Reset | SetZero() | not settable |
| Test emptiness | IsZero() | invalid Value |
| Fit check | OverflowInt(n), OverflowFloat(f) | wrong kind |
Slices, maps and arrays Important
In plain words: Collections have their own reflective operations: index into a slice, range over a map with MapRange, append with reflect.Append, create with MakeSlice and MakeMap.
Common misunderstanding: "I can set a map element through MapIndex(k).Set." MapIndex returns a copy that is not addressable; write with SetMapIndex(k, v). And SetMapIndex on a nil map panics with the ordinary assignment to entry in nil map: create it with MakeMap first.
Definition: Len(), Cap(), Index(i), Slice(i, j), SetLen(n), Grow(n), reflect.Append(s, x...), reflect.AppendSlice, reflect.Copy, reflect.Swapper(slice) (the function sort.Slice uses, through its internal twin), MapKeys(), MapIndex(k), MapRange() (iterator with Key() and Value()), SetMapIndex(k, v) (a zero Value as v deletes the key), Clear() (Go 1.21), Seq()/Seq2() (Go 1.23, iterate like range). Index out of range panics with reflect: slice index out of range.
Building a slice and a map at run time
1 s := reflect.MakeSlice(reflect.SliceOf(t), 0, n) []T with len 0, cap n
2 s = reflect.Append(s, elem) append returns the new slice Value
3 m := reflect.MakeMap(reflect.MapOf(kt, vt)) non-nil map[K]V
4 cur := m.MapIndex(key) zero Value when absent: check IsValid()
5 m.SetMapIndex(key, reflect.ValueOf(n + 1)) insert or update
6 m.SetMapIndex(key, reflect.Value{}) deleteReal scenario: a generic "group by field" helper builds map[K][]V with MapOf; a scanner builds []T for a type it learns at start-up; a diff tool ranges both maps with MapRange in a stable order by sorting keys, because map iteration order is random (the mini encoder sorts keys the same way encoding/json does).
| Operation | Slice | Array | Map |
|---|---|---|---|
| Length | Len() | Len() | Len() |
| Element read | Index(i) | Index(i) | MapIndex(k) |
| Element write | Index(i).Set* (addressable) | needs an addressable array | SetMapIndex(k, v) |
| Add | reflect.Append | not possible | SetMapIndex |
| Remove | reslice | not possible | SetMapIndex(k, reflect.Value{}) |
| Make | MakeSlice(SliceOf(t), len, cap) | reflect.New(ArrayOf(n, t)).Elem() | MakeMap(MapOf(k, v)) |
| Iterate | for i := range v.Len() | same | v.MapRange() or v.Seq2() |
Calling functions and methods: Call and MethodByName Important
In plain words: v.Call(args) runs a function Value with arguments given as []reflect.Value and returns its results the same way. v.MethodByName("Add") finds an exported method by name and returns it as a callable Value with the receiver already bound.
Common misunderstanding: "MethodByName finds any method." It finds only exported methods in the method set of the exact static type you hold: a value Calculator does not see methods with pointer receivers, but *Calculator sees both. And Call panics (it does not return an error) on a wrong argument count or type.
Definition: Value.Call(in []Value) []Value; Value.CallSlice for variadics passed as a slice; Value.Method(i), Value.NumMethod(), Type.Method(i) (an unbound Method whose function takes the receiver first), Type.NumMethod(). Call panics with reflect: Call with too few input arguments, reflect: Call with too many input arguments, or reflect: Call using string as type int. A method with an error as the last result returns it as an ordinary Value; converting it is your job. A panic inside the callee propagates through Call.
Calling by name, safely
1 m := reflect.ValueOf(recv).MethodByName(name) m.IsValid() false if missing or unexported
2 mt := m.Type() mt.NumIn(), mt.IsVariadic()
3 check len(args) against mt.NumIn() Call would panic, so return an error
4 check av.Type().AssignableTo(mt.In(i)) per argument
5 defer recover() the callee itself may panic
6 out := m.Call(in) results as []reflect.Value
7 last result implements error? turn it into an error valueReal scenario: a command console maps "user.disable" to a method; a test framework discovers TestXxx methods; net/rpc registers every exported method with the right signature; a template engine calls methods named in the template. Each of these also keeps an allow-list or a signature filter, which is the point of the security section.
// Package dyncall calls functions and methods by name with reflect.Value.Call,
// and shows the safe shape: an explicit allow-list built at compile time,
// argument checking before Call, and error and panic translation.
package dyncall
import (
"errors"
"fmt"
"reflect"
)
// Calculator is the receiver whose methods are exposed.
type Calculator struct{ Offset int }
// Add is exposed.
func (c Calculator) Add(a, b int) int { return a + b + c.Offset }
// Div is exposed and returns an error as its last result.
func (c Calculator) Div(a, b int) (int, error) {
if b == 0 {
return 0, errors.New("division by zero")
}
return a / b, nil
}
// Sum is exposed and variadic.
func (c Calculator) Sum(xs ...int) int {
t := 0
for _, x := range xs {
t += x
}
return t
}
// Boom panics, to show that Invoke converts a callee panic into an error.
func (c Calculator) Boom() { panic("boom") }
// Reset mutates the receiver, so it needs a pointer receiver.
func (c *Calculator) Reset() { c.Offset = 0 }
// unexported is invisible to MethodByName.
func (c Calculator) unexported() int { return 1 }
// Invoke calls the exported method name on recv with args. It reports problems
// as errors; a panic inside the callee is converted too.
func Invoke(recv any, name string, args ...any) (results []any, err error) {
rv := reflect.ValueOf(recv)
m := rv.MethodByName(name)
if !m.IsValid() {
return nil, fmt.Errorf("dyncall: %T has no exported method %q", recv, name)
}
mt := m.Type()
if !mt.IsVariadic() && len(args) != mt.NumIn() {
return nil, fmt.Errorf("dyncall: %s wants %d args, got %d", name, mt.NumIn(), len(args))
}
if mt.IsVariadic() && len(args) < mt.NumIn()-1 {
return nil, fmt.Errorf("dyncall: %s wants at least %d args, got %d", name, mt.NumIn()-1, len(args))
}
in := make([]reflect.Value, len(args))
for i, a := range args {
var want reflect.Type
if mt.IsVariadic() && i >= mt.NumIn()-1 {
want = mt.In(mt.NumIn() - 1).Elem()
} else {
want = mt.In(i)
}
av := reflect.ValueOf(a)
if !av.IsValid() || !av.Type().AssignableTo(want) {
return nil, fmt.Errorf("dyncall: arg %d of %s: %T is not assignable to %s", i, name, a, want)
}
in[i] = av
}
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("dyncall: %s panicked: %v", name, r)
}
}()
out := m.Call(in)
for _, o := range out {
results = append(results, o.Interface())
}
// Go convention: a trailing error result becomes the returned error.
if n := len(results); n > 0 {
if e, ok := results[n-1].(error); ok && e != nil {
return results[:n-1], e
}
if mt.Out(n-1) == reflect.TypeFor[error]() {
results = results[:n-1]
}
}
return results, nil
}
// Registry is the safe alternative to MethodByName on user input: a map from
// public names to functions that you chose at compile time.
type Registry map[string]reflect.Value
// NewRegistry validates every function once, at startup.
func NewRegistry(fns map[string]any) (Registry, error) {
r := Registry{}
for name, fn := range fns {
v := reflect.ValueOf(fn)
if v.Kind() != reflect.Func {
return nil, fmt.Errorf("dyncall: %q is %T, not a func", name, fn)
}
r[name] = v
}
return r, nil
}
// Call runs a registered function; unknown names are an error, never a lookup
// into the type system.
func (r Registry) Call(name string, args ...any) ([]any, error) {
fn, ok := r[name]
if !ok {
return nil, fmt.Errorf("dyncall: %q is not registered", name)
}
if len(args) != fn.Type().NumIn() {
return nil, fmt.Errorf("dyncall: %s wants %d args, got %d", name, fn.Type().NumIn(), len(args))
}
in := make([]reflect.Value, len(args))
for i, a := range args {
av := reflect.ValueOf(a)
if !av.IsValid() || !av.Type().AssignableTo(fn.Type().In(i)) {
return nil, fmt.Errorf("dyncall: arg %d of %s: %T is not assignable to %s", i, name, a, fn.Type().In(i))
}
in[i] = av
}
var out []any
for _, o := range fn.Call(in) {
out = append(out, o.Interface())
}
return out, nil
}
// Methods lists the exported method names of a value: the method set is part
// of the type, and a pointer receiver has more methods than a value.
func Methods(v any) []string {
t := reflect.TypeOf(v)
names := make([]string, 0, t.NumMethod())
for i := 0; i < t.NumMethod(); i++ {
names = append(names, t.Method(i).Name)
}
return names
}| Case | What happens |
|---|---|
| Unknown or unexported name | MethodByName returns the zero Value; check IsValid() |
| Pointer-receiver method on a value | invisible; pass &c |
| Variadic function | pass the extra arguments individually; Call builds the slice |
| Argument of the wrong type | panic reflect: Call using string as type int |
nil argument | reflect.ValueOf(nil) is invalid; use reflect.Zero(t) for a typed nil |
| Callee panics | the panic unwinds through Call; recover where you call |
| Call on a method value of an unexported field | panics |
Making types and values at run time Important
In plain words: reflect.New(t) allocates a zero value of a type known only at run time and returns a pointer to it. reflect.MakeSlice, MakeMap, MakeChan and MakeFunc make the composite kinds. SliceOf, MapOf, ArrayOf, ChanOf, FuncOf, PointerTo and StructOf make new types.
Common misunderstanding: "StructOf lets me define a type with methods and private fields." StructOf makes anonymous struct types; it cannot add methods, cannot create unexported fields (it panics with reflect.StructOf: field "x" is unexported but missing PkgPath), and does not support promoted methods of embedded fields.
Definition: func New(typ Type) Value returns a Value of kind Pointer; .Elem() is the settable zero value, .Interface() is a typed pointer such as *T boxed in any. func Zero(typ Type) Value returns an unaddressable zero. func StructOf(fields []StructField) Type builds the struct type; the type is cached by the runtime, so equal field lists give the same Type. MakeFunc(typ, fn) returns a function Value whose body is your func([]Value) []Value, which is how generic wrappers and mocks are written without generics.
Types made at run time
1 t := reflect.StructOf([]reflect.StructField{
2 {Name: "Name", Type: stringT, Tag: `json:"name"`},
3 {Name: "Age", Type: intT, Tag: `json:"age"`},
4 }) an anonymous struct type
5 p := reflect.New(t) *struct{Name string "json:\"name\""; Age int "json:\"age\""}
6 p.Elem().FieldByName("Name").SetString("Ada")
7 json.Marshal(p.Interface()) {"name":"Ada","age":0}Real scenario: a schema-driven API builds a decode target from a JSON Schema at start-up; a mock generator uses MakeFunc to stand in for any function signature; a test fixture builder creates a slice of whatever struct the test asks for; a GraphQL layer builds result types from a schema.
// Package maker builds values and types at run time: New, MakeSlice, MakeMap,
// SliceOf, MapOf, StructOf, MakeFunc, Convert, Implements and AssignableTo.
package maker
import (
"fmt"
"go/token"
"reflect"
"strings"
)
// Stringer is a local interface for Implements.
type Stringer interface{ String() string }
// ID has a String method on the value receiver.
type ID int
func (i ID) String() string { return fmt.Sprintf("ID-%d", int(i)) }
// Handle has String on the pointer receiver only.
type Handle struct{ n int }
func (h *Handle) String() string { return fmt.Sprintf("handle-%d", h.n) }
// NewOf allocates a *T for a Type known only at run time and returns it as any.
func NewOf(t reflect.Type) any { return reflect.New(t).Interface() }
// MakeIntSlice builds []T for any integer Kind with len and cap, then appends.
func MakeIntSlice(t reflect.Type, vals ...int64) any {
s := reflect.MakeSlice(reflect.SliceOf(t), 0, len(vals))
for _, n := range vals {
e := reflect.New(t).Elem()
e.SetInt(n)
s = reflect.Append(s, e)
}
return s.Interface()
}
// MakeCounter builds a map[string]int at run time and fills it.
func MakeCounter(words []string) map[string]int {
m := reflect.MakeMap(reflect.MapOf(reflect.TypeFor[string](), reflect.TypeFor[int]()))
for _, w := range words {
k := reflect.ValueOf(w)
cur := m.MapIndex(k) // zero Value when absent
n := 0
if cur.IsValid() {
n = int(cur.Int())
}
m.SetMapIndex(k, reflect.ValueOf(n+1))
}
return m.Interface().(map[string]int)
}
// DynamicStruct creates a struct type with the given exported fields and tags
// and returns a pointer to a new zero value. StructOf panics on unexported
// field names, so names are checked first.
func DynamicStruct(fields map[string]reflect.Type, order []string) (any, error) {
sfs := make([]reflect.StructField, 0, len(order))
for _, name := range order {
t, ok := fields[name]
if !ok {
return nil, fmt.Errorf("maker: no type for %q", name)
}
sf := reflect.StructField{
Name: name,
Type: t,
Tag: reflect.StructTag(fmt.Sprintf(`json:%q`, strings.ToLower(name))),
}
// sf.IsExported() is not usable here: PkgPath is empty on a hand-built field.
if !token.IsExported(name) {
return nil, fmt.Errorf("maker: field %q is not exported", name)
}
sfs = append(sfs, sf)
}
return reflect.New(reflect.StructOf(sfs)).Interface(), nil
}
// Swap returns a function with the signature func(A, B) (B, A), made with
// MakeFunc for the given types.
func Swap(a, b reflect.Type) any {
ft := reflect.FuncOf([]reflect.Type{a, b}, []reflect.Type{b, a}, false)
f := reflect.MakeFunc(ft, func(in []reflect.Value) []reflect.Value {
return []reflect.Value{in[1], in[0]}
})
return f.Interface()
}
// Relations reports what the type predicates say about T and the Stringer
// interface for a value and its pointer.
func Relations() map[string]bool {
st := reflect.TypeFor[Stringer]()
id, h := reflect.TypeFor[ID](), reflect.TypeFor[Handle]()
return map[string]bool{
"ID implements Stringer": id.Implements(st),
"Handle implements Stringer": h.Implements(st),
"*Handle implements Stringer": reflect.PointerTo(h).Implements(st),
"ID assignable to int": id.AssignableTo(reflect.TypeFor[int]()),
"ID convertible to int": id.ConvertibleTo(reflect.TypeFor[int]()),
"ID assignable to Stringer": id.AssignableTo(st),
"[]int comparable": reflect.TypeFor[[]int]().Comparable(),
"string comparable": reflect.TypeFor[string]().Comparable(),
}
}
// Convert converts x to the named kind target, for example int to ID or
// float64 to int. It returns an error where Value.Convert would panic.
func Convert(x any, target reflect.Type) (any, error) {
v := reflect.ValueOf(x)
if !v.Type().ConvertibleTo(target) {
return nil, fmt.Errorf("maker: %s is not convertible to %s", v.Type(), target)
}
return v.Convert(target).Interface(), nil
}| Need | Call | Result |
|---|---|---|
A new *T | reflect.New(t) | pointer Value, .Elem() is settable |
| An unaddressable zero | reflect.Zero(t) | read-only zero value |
| A slice type from an element type | reflect.SliceOf(t) | type []T |
| A map type | reflect.MapOf(k, v) | type map[K]V |
| A pointer type | reflect.PointerTo(t) | type *T |
| A function type | reflect.FuncOf(in, out, variadic) | type func(...) |
| A struct type | reflect.StructOf(fields) | anonymous struct, exported fields only |
| A function body | reflect.MakeFunc(ft, impl) | callable function Value |
| A named type or a type with methods | impossible | write it in source or generate it |
Type relations: Implements, AssignableTo, ConvertibleTo, Comparable Important
In plain words: Before you set, convert or call, ask the types: does T implement this interface, may a T be assigned to that type, can it be converted, can two values be compared with ==.
Common misunderstanding: "If *T implements Stringer, so does T." The method set of T excludes pointer-receiver methods. reflect.TypeFor[Handle]().Implements(stringerType) is false while reflect.TypeFor[*Handle]().Implements(stringerType) is true. The interface argument must itself be an interface type; passing a concrete type panics.
Definition: Type.Implements(u Type) bool, Type.AssignableTo(u Type) bool, Type.ConvertibleTo(u Type) bool, Type.Comparable() bool, Value.CanConvert(t), Value.Comparable() (checks the dynamic type), Value.Equal(u). To get the Type of an interface, use reflect.TypeFor[error]() (Go 1.22) rather than the older reflect.TypeOf((*error)(nil)).Elem().
Type relations from the maker snippet
1 stringer := reflect.TypeFor[Stringer]()
2 ID implements Stringer true (value receiver)
3 Handle implements Stringer false (pointer receiver only)
4 *Handle implements Stringer true
5 ID assignable to int false (distinct named type)
6 ID convertible to int true
7 []int comparable false (slices are not comparable)Real scenario: a JSON library checks Implements(marshalerType) on T and on *T to choose a custom encoder; a DI container checks AssignableTo between a registered implementation and a requested interface; a map-key helper checks Comparable() before using a value as a key.
| Test | Typical use | Pitfall |
|---|---|---|
t.Implements(iface) | pick custom marshalers | check PointerTo(t) too |
t.AssignableTo(u) | before Set | a named type is not assignable to its underlying type |
t.ConvertibleTo(u) | before Convert | convertible does not mean lossless |
t.Comparable() | before using as a key | a struct with a slice field is not comparable |
v.Comparable() | before == on Interface() values | checks the dynamic type for interfaces |
DeepEqual: semantics and pitfalls Must-know
In plain words: reflect.DeepEqual(a, b) walks two values of the same type and compares them recursively: struct fields (even unexported ones), slice and array elements, map entries, what pointers point to. It is the quick way to compare in a test, and its definition of "equal" has sharp corners.
Common misunderstanding: "DeepEqual is == for big values." It is a relaxation of == with its own rules: a nil slice is not equal to an empty slice, NaN is not equal to itself, two non-nil functions are never equal, values of different types are never equal even if they print the same, and unexported fields are compared even though your code cannot see them.
Definition: the package documentation says that two values of identical type are deeply equal if one of the following applies: arrays element by element; structs field by field, "both exported and unexported"; funcs only if both nil; interfaces when they hold deeply equal concrete values; maps when both nil or both non-nil, same length and the keys (matched with ==) map to deeply equal values; pointers when equal with == or pointing to deeply equal values; slices when both nil or both non-nil, same length and same first element address or deeply equal elements; everything else with ==. Cycles are handled: repeated pointer pairs are assumed equal, so the walk terminates. "Values of distinct types are never deeply equal."
DeepEqual outcomes (all asserted in deepeq_test.go)
1 DeepEqual([]int(nil), []int{}) false nil slice vs empty slice
2 DeepEqual(map[string]int(nil), map[string]int{}) false nil map vs empty map
3 DeepEqual(math.NaN(), math.NaN()) false NaN != NaN
4 p := &nan; DeepEqual(p, p) true same pointer, equal by ==
5 DeepEqual([]float64{nan}, []float64{nan}) false NaN inside a slice
6 f := func(){}; DeepEqual(f, f) false non-nil funcs never equal
7 DeepEqual(1, int64(1)) false different types
8 DeepEqual(Order{note:"a"}, Order{note:"b"}) false unexported field compared
9 DeepEqual(utc, sameInstantOtherZone) false time.Time has a *Location fieldReal scenario: a table test compares a decoded []Item{} with an expected nil slice and fails with identical-looking output; a cache test compares two time.Time values read from the database and the zone pointer differs; a fixture compare fails because an unexported mu sync.Mutex changed state. Go 1.23 notes also record a bug fix where DeepEqual on netip.Addr values with an IPv4 and an IPv4-mapped IPv6 address wrongly reported equal; the lesson is that DeepEqual follows representation, not meaning.
// Package deepeq collects the cases where reflect.DeepEqual surprises, and the
// go-cmp alternative that explains differences and takes options.
package deepeq
import (
"math"
"reflect"
"time"
"github.com/google/go-cmp/cmp"
"github.com/google/go-cmp/cmp/cmpopts"
)
// Order has an unexported field: DeepEqual compares it, cmp panics on it.
type Order struct {
ID int
Items []string
Meta map[string]string
note string
}
// Cases returns name -> DeepEqual result for the classic surprises.
func Cases() map[string]bool {
nan := math.NaN()
f := func() {}
var nilS []int
p := &nan
type pair struct{ A, B any }
return map[string]bool{
"nil slice vs empty slice": reflect.DeepEqual(nilS, []int{}),
"nil map vs empty map": reflect.DeepEqual(map[string]int(nil), map[string]int{}),
"NaN vs NaN": reflect.DeepEqual(nan, nan),
"same pointer to NaN": reflect.DeepEqual(p, p),
"slice containing NaN": reflect.DeepEqual([]float64{nan}, []float64{nan}),
"func vs same func": reflect.DeepEqual(f, f),
"nil func vs nil func": reflect.DeepEqual((func())(nil), (func())(nil)),
"int vs int64 (different type)": reflect.DeepEqual(1, int64(1)),
"interface holding same": reflect.DeepEqual(pair{1, "a"}, pair{1, "a"}),
"unexported fields differ": reflect.DeepEqual(Order{note: "a"}, Order{note: "b"}),
"time same instant, other zone": reflect.DeepEqual(time.Unix(0, 0).UTC(), time.Unix(0, 0).In(time.FixedZone("X", 3600))),
}
}
// Cyclic shows that DeepEqual terminates on a cycle.
type Cyclic struct {
Name string
Next *Cyclic
}
// CyclicEqual compares two separately built two-node cycles.
func CyclicEqual() bool {
a1 := &Cyclic{Name: "a"}
a2 := &Cyclic{Name: "b", Next: a1}
a1.Next = a2
b1 := &Cyclic{Name: "a"}
b2 := &Cyclic{Name: "b", Next: b1}
b1.Next = b2
return reflect.DeepEqual(a1, b1)
}
// Diff compares two orders with go-cmp, ignoring the unexported field and
// treating nil and empty collections as equal, and returns the report.
func Diff(want, got Order) string {
return cmp.Diff(want, got,
cmpopts.IgnoreUnexported(Order{}),
cmpopts.EquateEmpty(),
)
}
// FloatsClose compares floats with a tolerance and NaN == NaN.
func FloatsClose(a, b []float64) bool {
return cmp.Equal(a, b, cmpopts.EquateApprox(0, 1e-9), cmpopts.EquateNaNs())
}
// StrictDiffPanics reports the text of the panic go-cmp raises on an
// unexported field when no option handles it.
func StrictDiffPanics() (msg string) {
defer func() {
if r := recover(); r != nil {
msg, _ = r.(string)
}
}()
_ = cmp.Equal(Order{}, Order{})
return ""
}| Case | DeepEqual | What to use instead |
|---|---|---|
| nil versus empty slice or map | false | cmpopts.EquateEmpty() or normalise before comparing |
NaN values | false | cmpopts.EquateNaNs() or math.IsNaN |
time.Time | representation-sensitive | t1.Equal(t2), cmpopts.EquateApproxTime |
| Funcs | false unless both nil | compare behaviour, not funcs |
| Unexported fields | compared | cmpopts.IgnoreUnexported |
| Floating tolerance | exact bits | cmpopts.EquateApprox(0, 1e-9) |
| Ordering of a set-like slice | order matters | cmpopts.SortSlices |
error values | pointer or representation | errors.Is, errors.As |
go-cmp: a more explicit DeepEqual Important
In plain words: github.com/google/go-cmp/cmp is a comparison library for tests. It compares like DeepEqual but lets you say how (options), refuses what it cannot compare safely (it panics on unexported fields unless told), and returns a readable diff.
Common misunderstanding: "cmp.Equal is just a faster DeepEqual." It is stricter and more informative, not faster. Its README describes the package as "intended to be a more powerful and safer alternative to reflect.DeepEqual for comparing whether two values are semantically equal". It also does not compare unexported fields by default: it panics instead of reaching in.
Definition: cmp.Equal(x, y, opts...) bool and cmp.Diff(x, y, opts...) string. Options: cmpopts.IgnoreUnexported(T{}), cmpopts.IgnoreFields, cmpopts.EquateEmpty(), cmpopts.EquateNaNs(), cmpopts.EquateApprox, cmpopts.SortSlices, cmp.Comparer, cmp.Transformer, cmp.AllowUnexported. An Equal(T) bool method on a type is used automatically. Compared with DeepEqual, the output tells you which path differed.
cmp.Diff(want, got) for an Order whose ID differs
deepeq.Order{
- ID: 1,
+ ID: 2,
Items: {"a"},
Meta: nil,
... // 1 ignored field
}Real scenario: a repository test asserts cmp.Diff(want, got, cmpopts.IgnoreFields(Order{}, "UpdatedAt")) == ""; a protobuf test uses protocmp.Transform() (a separate module in the same ecosystem); a golden-file test prints the diff in the failure message.
| Aspect | reflect.DeepEqual | cmp.Equal / cmp.Diff |
|---|---|---|
| Part of | standard library | external module github.com/google/go-cmp |
| Unexported fields | compared | panic unless IgnoreUnexported or AllowUnexported |
| Custom equality | none | Equal methods, Comparer, Transformer |
| Output | bool only | Diff returns a path-annotated diff |
| nil versus empty | different | different unless EquateEmpty |
| Intended for | quick checks, production-safe walks | tests only (it may panic on surprising types) |
TypeFor, Seq and the version table Good to know
In plain words: Some convenient APIs arrived late. reflect.TypeFor[T]() (Go 1.22) is the clean way to get a Type for a type you know at compile time. Others make iteration and conversion cheaper.
Common misunderstanding: "reflect.TypeOf((*T)(nil)).Elem() and TypeFor[T]() are different things." They give the same Type; the second is shorter and, for an interface type T, the only readable way to ask for the interface itself. The stdversion vet analyzer in Go 1.23 even uses reflect.TypeFor as its example of a symbol that is too new for a go 1.21 module.
Definition: the module's go directive decides which APIs are allowed; the snippets in this chapter use go 1.24, so TypeFor, Value.Seq and Value.Clear are available while reflect.TypeAssert (Go 1.25) and the Go 1.26 iterators are only described.
| Go | Addition | Use |
|---|---|---|
| 1.17 | reflect.VisibleFields, StructField.IsExported, Value.CanConvert | fields reachable by name, readable export check, safe conversion check |
| 1.18 | reflect.Pointer and PointerTo (renaming Ptr, PtrTo), Value.CanInt/CanUint/CanFloat, SetIterKey, FieldByIndexErr, UnsafePointer | clearer kinds, safe getters, nil-embedded-pointer errors |
| 1.20 | Value.SetZero, Value.Grow, Value.Comparable, Value.Equal | zero, grow and compare helpers |
| 1.21 | ValueOf no longer forces heap escape; Value.Clear | stack-friendly values; clear a map or slice |
| 1.22 | reflect.TypeFor[T](); PtrTo deprecated; Value.IsZero true for negative zero | typed type lookups, consistent zero test |
| 1.23 | Value.Seq, Value.Seq2, Type.CanSeq, Type.CanSeq2, Type.OverflowInt and siblings, SliceAt | range-style iteration |
| 1.25 | reflect.TypeAssert[T](v) | assert without allocation |
| 1.26 | Type.Fields, Type.Methods, Type.Ins, Type.Outs, Value.Fields, Value.Methods | iterators over fields and methods |
Every row is taken from the Go 1.17, 1.18, 1.20, 1.21, 1.22, 1.23, 1.25 and 1.26 release notes saved for this chapter.
Performance: allocation, the type cache and Go 1.21 Must-know
In plain words: Reflection is slower than direct code for three reasons: it works through indirection instead of known offsets, it looks things up by name or by tag string, and it boxes values into any (which can allocate). You can remove most of the cost by doing the lookups once per type and reusing the result.
Common misunderstanding: "Reflection allocates on every call." Reading and setting through a held Value does not. FieldByName, tag parsing, Interface() of a non-pointer value, reflect.New and MakeSlice are the usual allocation or lookup costs; since Go 1.21 reflect.ValueOf no longer forces its argument onto the heap, so the "ValueOf always escapes" advice is out of date.
Definition: the cure is a type cache: a sync.Map (or a mutex and a map) keyed by reflect.Type that stores a pre-computed plan (field index paths, parsed tags, chosen setters). encoding/json does this for its encoders and field lists; sqlx and pgx do it for column-to-field maps; the validator in this chapter does it for parsed rules. Type values are comparable and cheap to hash, which is why they are the key.
Measured on one Apple M4 Pro, Go 1.27.4 (go test -bench, real output)
1 BenchmarkDirect 0.2485 ns/op 0 B/op 0 allocs/op r.Score = i
2 BenchmarkReflectByIndex 1.356 ns/op 0 B/op 0 allocs/op f.SetInt with a held Value
3 BenchmarkReflectByName 24.34 ns/op 0 B/op 0 allocs/op v.FieldByName("Score").SetInt
4 BenchmarkTagLookupEveryTime 77.85 ns/op 0 B/op 0 allocs/op 3 fields, Tag.Lookup each
5 BenchmarkTagFromCache 1.029 ns/op 0 B/op 0 allocs/op same data from a precomputed slice
6 BenchmarkInterfaceAlloc 11.13 ns/op 16 B/op 1 allocs/op v.Field(1).Interface() on a stringReal scenario: a request validator that re-parses validate:"..." tags on every request shows up at 30 percent of CPU in a profile; caching the plan per type drops it below noise. A row scanner that calls FieldByName for each column of every row of a million-row export is the same bug with a different name.
// Package bench measures what reflection costs: a direct field write, a
// reflect write by index, a reflect write by name, a cached reflect plan, and
// the tag-parsing work that a type cache removes.
package bench
import (
"reflect"
"strconv"
"testing"
)
type Row struct {
ID int64 `db:"id"`
Name string `db:"name"`
Score int `db:"score"`
}
var sink Row
func BenchmarkDirect(b *testing.B) {
var r Row
for i := 0; i < b.N; i++ {
r.Score = i
}
sink = r
}
func BenchmarkReflectByIndex(b *testing.B) {
var r Row
f := reflect.ValueOf(&r).Elem().Field(2)
for i := 0; i < b.N; i++ {
f.SetInt(int64(i))
}
sink = r
}
func BenchmarkReflectByName(b *testing.B) {
var r Row
v := reflect.ValueOf(&r).Elem()
for i := 0; i < b.N; i++ {
v.FieldByName("Score").SetInt(int64(i))
}
sink = r
}
func BenchmarkTagLookupEveryTime(b *testing.B) {
t := reflect.TypeFor[Row]()
n := 0
for i := 0; i < b.N; i++ {
for j := 0; j < t.NumField(); j++ {
if v, ok := t.Field(j).Tag.Lookup("db"); ok {
n += len(v)
}
}
}
_ = strconv.Itoa(n)
}
var cached = func() []string {
t := reflect.TypeFor[Row]()
out := make([]string, t.NumField())
for j := range out {
out[j] = t.Field(j).Tag.Get("db")
}
return out
}()
func BenchmarkTagFromCache(b *testing.B) {
n := 0
for i := 0; i < b.N; i++ {
for _, v := range cached {
n += len(v)
}
}
_ = strconv.Itoa(n)
}
func BenchmarkInterfaceAlloc(b *testing.B) {
r := Row{ID: 1, Name: "Ada", Score: 3}
v := reflect.ValueOf(&r).Elem()
var out any
b.ReportAllocs()
for i := 0; i < b.N; i++ {
out = v.Field(1).Interface() // boxes the string: allocates
}
_ = out
}| Cost | Where it comes from | Remedy |
|---|---|---|
FieldByName, MethodByName | linear or map lookup by string on every call | resolve once to an index path; keep []int |
Tag.Get, Tag.Lookup | string parsing on every call | parse at first use; store in the plan |
Interface() | boxing allocates for non-pointer values | use Int(), String(); or reflect.TypeAssert (1.25) |
reflect.New, MakeSlice, MakeMap | real allocations | reuse buffers; pool with sync.Pool |
Type lookups for generics | none (compile-time) | prefer generics when types are known |
| Contention on a global cache | a mutex around every read | sync.Map or build immutable plans and publish with atomic.Pointer |
| Cold start | first call per type builds the plan | warm up at start-up for latency-sensitive paths |
Alternatives: generics, interfaces and go generate Must-know
In plain words: Before reaching for reflection, ask whether the compiler can do the job. If the type is known when you write the code, an interface or generics is safer and faster. If it is the same boilerplate for many types, generate it.
Common misunderstanding: "Generics replace reflection." Generics remove the need for reflection when the algorithm is the same and the types are known at compile time (a Map[T, U] function, a typed Set[T]). They cannot inspect a struct's fields, read tags, or create a type from a schema; for that you still need reflection or generated code.
Definition: go generate runs commands written as //go:generate comments; it "is not part of go build" (Go blog, Generating code), so generated files are committed and reviewed. Typical generators: stringer (enum String()), easyjson, msgp, sqlc, protoc-gen-go, mockgen. The trade is build-time complexity for run-time speed and compile-time checking.
Choosing between the four options
1 Known types, same algorithm -> generics or an interface
2 Known types, per-type boilerplate -> hand-written code, or go generate
3 Types discovered at run time -> reflect, behind a cached small package
4 Hot path with many known types -> go generate, then benchmark bothReal scenario: encoding/json stays reflective because users bring arbitrary types, while a hot internal event type gets a generated marshaller; sqlc generates typed Go from SQL so no reflection happens per row; a slices.SortFunc replaces sort.Slice with a reflective swapper once the element type is known.
| Technique | Checked when | Speed | Cost to the team |
|---|---|---|---|
| Plain code, interfaces | compile time | fastest | write each type |
| Generics | compile time | fast | cannot see fields or tags |
go generate | build time (and generated code compiles) | fast | generator in the toolchain, committed output |
reflect | run time | slower; mitigable | panics, harder review |
reflect plus unsafe | nothing | fastest reflective | memory-safety risk |
For how go generate and tools fit a project, see Toolchain, Modules & Packages and Project Layout, golangci-lint, Makefile, Docker & Multi-Binary Builds.
In the wild: encoding/json, fmt, ORMs, validators, DI Important
In plain words: Reflection is the engine under every "give me any struct" library. Knowing which libraries use it tells you where your own code will meet its limits.
Common misunderstanding: "My ORM or validator is magic." It is the loops from this page: read tags, build a plan per reflect.Type, cache it, write values through pointers.
Definition: the usual users are encoding/json and encoding/xml (struct fields, tags, Marshaler detection through Implements), fmt (the %v and %+v verbs), text/template and html/template (field and method lookup by name), database/sql argument conversion and sqlx/pgx scanning into structs by column name, validators such as go-playground/validator, dependency-injection containers that read a constructor's parameter types, test helpers (go-cmp, testify's assert.Equal), and net/rpc. Whether a given third-party library uses reflect for a specific feature is general knowledge here, except where the standard library source was read.
Where reflect shows up in one HTTP request
1 net/http handler -> json.NewDecoder(r.Body).Decode(&in) json: struct fields and tags by reflection
2 validator.Struct(in) -> tags parsed once per type, cached
3 sqlx.Get(&row, query, args...) -> column names mapped to fields by `db` tag
4 json.NewEncoder(w).Encode(out) -> encoder chosen per type from a cache
5 log.Info("done", "user", u) -> slog/fmt walks the value with %+vReal scenario: a service decodes JSON into a struct, validates it, writes a row with sqlx and logs it with %+v: four reflective passes over one type, each with its own cache. The cost is invisible until a type with 400 fields or a request rate of 50 000 per second makes it visible.
| Library or package | What it reflects over | What is cached | If it fails |
|---|---|---|---|
encoding/json | struct fields, tags, Marshaler methods | encoder and field list per Type | errors such as json: unsupported type: chan int |
fmt | any value for %v, %+v, %#v | none; walks every time | prints %!v(PANIC=...) if a method panics |
text/template | fields and methods by name | none | execution error naming the field |
sqlx, pgx.RowToStructByName | db tags, columns | column map per Type | missing destination name x (sqlx) |
go-playground/validator | validate tags | parsed rules per Type | panics for an unknown tag at first use |
DI container (for example uber-go/dig) | constructor parameter and result types | graph of providers | an error naming the missing type |
go-cmp, testify | any value for diffs | none | readable diff |
net/rpc | exported methods and their signatures | service map | registration error log |
Security: never reflect over untrusted type names Must-know
In plain words: Reflection cannot turn a string into a type (Go has no registry of type names), but it can call any exported method by a string and set any exported field by a string. Letting a request choose those strings gives the request the program's whole exported API.
Common misunderstanding: "It is safe because Go has no eval." MethodByName(userInput).Call(...) is an eval of your exported methods. Fields are the same: a form binder that sets any field by name lets a client set IsAdmin through ?is_admin=true, a well-known mass-assignment bug in every framework.
Definition: the safe pattern is an allow-list built at compile time: a map[string]func(...) or a registry (dyncall.Registry) validated at start-up, with argument checking. For binders, bind into a dedicated input struct (a DTO) that has only the fields clients may set, and reject unknown keys. For decoders, never use reflect.New on a Type derived from untrusted data (type confusion, memory pressure); encoding/gob and unsafe usage belong in the same warning. Reflection over untrusted type names is also unavailable in the first place: reflect has no TypeByName; any lookup of a type by string is a registry you built, and that registry is your allow-list.
Allow-list versus MethodByName
1 GET /admin/run?cmd=Shutdown attacker chooses cmd
2 reflect.ValueOf(svc).MethodByName(cmd).Call(nil) BAD: any exported method runs
3 registry.Call(cmd, args...) GOOD: unknown name -> error, argument types checked
4 registry built at start-up from a literal map only the functions you listed existReal scenario: a debug console exposed by MethodByName on a service struct; a "patch any field" endpoint that sets Role; a plugin loader that maps a type string from YAML to a constructor through a global map without an allow-list; a template engine given user-controlled templates calling methods on a rich object (server-side template injection, see Strings, Runes, fmt Verbs, text/template & regexp).
| Risk | Example | Defence |
|---|---|---|
| Arbitrary method call | MethodByName(userInput) | allow-list map built at compile time |
| Mass assignment | bind request into the domain struct | bind into a DTO, copy fields explicitly |
| Type confusion | reflect.New(typeFromInput) | a closed set of constructors |
| Panic on bad data | Call with user arguments | validate counts and types, recover at the edge |
| Resource use | deep or cyclic structures | depth limit, as in miniencode |
| Reading private data | unsafe to bypass CanInterface | do not; export what must be exported |
unsafe, reflectlite and what go vet cannot see Good to know
In plain words: unsafe can bypass what reflection forbids; internal/reflectlite is a slim copy of reflect used inside the standard library; go vet checks a little of this and cannot see most of it.
Common misunderstanding: "go vet will warn me about bad reflection." It checks tag syntax (structtag) and a few calls, but it cannot know that ValueOf(x).SetString is applied to an unaddressable value, because that depends on run-time values. The panic text is the compiler-free equivalent.
Definition: reflect.SliceHeader and StringHeader are deprecated in favour of unsafe.Slice and unsafe.SliceData. Value.UnsafeAddr, Value.UnsafePointer and reflect.NewAt expose raw pointers; using them breaks the safety guarantees described in the specification's section on the unsafe package. internal/reflectlite exists so that packages such as errors and sort can use a few reflection operations without importing the whole reflect package: the standard library source shows errors.As calling reflectlite.TypeOf(target).Comparable() and sort.Slice calling reflectlite.Swapper. Application code cannot import it (the internal rule).
What go vet says and what it does not
1 type T struct { A string `json:name` } go vet: struct field tag `json:name` not compatible with reflect.StructTag.Get: bad syntax for struct tag value
2 reflect.ValueOf("x").SetString("y") go vet: no warning
3 go run . panic: reflect: reflect.Value.SetString using unaddressable valueReal scenario: a linter rule forbids importing unsafe outside two packages; a performance fix replaces reflect.SliceHeader with unsafe.Slice; a bug report shows errors.As panicking with errors: target must be a non-nil pointer (the message comes from the standard library, not from reflect) because a caller passed a value instead of a pointer.
| Item | Status | Guidance |
|---|---|---|
reflect.SliceHeader, StringHeader | deprecated | unsafe.Slice, unsafe.String |
Value.UnsafeAddr | legacy | uintptr(v.Addr().UnsafePointer()) per the documentation |
reflect.NewAt, SliceAt | needs unsafe.Pointer | only for FFI and serialisation internals |
internal/reflectlite | stdlib only | cannot be imported by you |
go vet structtag | checks tag syntax | run it in CI |
go vet and reflect misuse | cannot detect | tests and recovered panics are the guard |
Mechanics
What a Value and a Type are made of Good to know
In plain words: A reflect.Value is a small struct: a pointer to the type description, a pointer to the data, and a flags word. The flags are where "addressable" and "read-only" live, which is why CanSet is a flag test and not a search.
Common misunderstanding: "Two Values are equal if == says so." The Value source comment says to compare the results of Interface, because "Using == on two Values does not compare the underlying values they represent". Type values, in contrast, are comparable and unique per type, so t1 == t2 is the right test.
Definition: from reflect/value.go (read in the Go source viewer): Value has typ_ *abi.Type, ptr unsafe.Pointer and an embedded flag. The lowest five bits of flag give the Kind; the next bits are flagStickyRO (obtained via an unexported non-embedded field), flagEmbedRO (via an unexported embedded field), flagIndir (ptr points at the data), flagAddr (CanAddr is true) and flagMethod. The interface variable that ValueOf receives is itself the (type, data) pair the Go blog describes, which is why reflection starts from an interface.
Where the flags come from
1 ValueOf(x) flag = Kind, no flagAddr CanAddr false, CanSet false
2 ValueOf(&x).Elem() flagAddr|flagIndir CanAddr true, CanSet true
3 .Field(i) on an exported field inherits flagAddr CanSet true
4 .Field(i) on a lower-case name adds flagStickyRO CanSet false, Interface panics
5 .Field(i) on an embedded lower-case type adds flagEmbedRO exported promoted fields stay usableReal scenario: reading reflect source is how you learn why Interface() panics on one field and not on its sibling, or why a promoted field of an unexported embedded struct is writable while the embedded struct itself is not.
A Value "can be used concurrently by multiple goroutines provided that the underlying Go value can be used concurrently for the equivalent direct operations" (same source comment); reflection adds no locks of its own, so your cache needs one.
Every panic text Must-know
In plain words: Almost every reflection error is a panic whose text starts with reflect: or reflect.. Reading the text tells you the method, the kind and what was wrong. All texts below were produced by running Go 1.27.4 and are asserted in the chapter's tests.
Common misunderstanding: "Panics mean the library is broken." They mean your call violated a documented precondition; reflect has no error returns, so the preconditions are the API. Wrap reflective calls that touch untrusted data in a helper that checks the precondition and returns an error (the snippets do this).
Definition: the catalogue below groups the texts by what you did wrong.
Panic texts, verbatim (Go 1.27.4)
1 reflect: reflect.Value.SetString using unaddressable value ValueOf(x) then Set
2 reflect: reflect.Value.SetInt using value obtained using unexported field Set on a private field
3 reflect.Value.Interface: cannot return value obtained from unexported field or method
4 reflect: call of reflect.Value.SetString on int Value wrong kind for the setter
5 reflect: call of reflect.Value.Elem on struct Value Elem on a non-pointer
6 reflect: NumField of non-struct type int Type method on the wrong kind
7 reflect: call of reflect.Value.Field on int Value Value method on the wrong kind
8 reflect: call of reflect.Value.Type on zero Value ValueOf(nil) or a missing field
9 reflect.Set: value of type string is not assignable to type int
10 reflect.Value.Convert: value of type string cannot be converted to type []int
11 reflect: Call using string as type int
12 reflect: Call with too few input arguments
13 reflect: slice index out of range
14 reflect.StructOf: field "x" is unexported but missing PkgPath
15 assignment to entry in nil map SetMapIndex on a nil mapReal scenario: a production crash log shows reflect: call of reflect.Value.Field on zero Value: a nil embedded pointer or a missing key reached Field; the fix is IsValid() before using the result of FieldByName or Elem().
| Text starts with | Cause | Fix |
|---|---|---|
... using unaddressable value | Set* on a copy | pass a pointer, take Elem() |
... using value obtained using unexported field | Set* on a private field | check CanSet() |
...Interface: cannot return value obtained from unexported field or method | Interface() on a private field | check CanInterface() |
call of reflect.Value.X on K Value | method X invalid for kind K | switch on Kind() first |
X of non-struct type T | Type struct method on another kind | check t.Kind() == reflect.Struct |
call of reflect.Value.X on zero Value | invalid Value | check IsValid() |
reflect.Set: value of type A is not assignable to type B | assignment mismatch | AssignableTo or Convert |
reflect: Call using A as type B | wrong argument | check AssignableTo per argument |
reflect: Call with too few/many input arguments | arity | compare with Type.NumIn() |
reflect.StructOf: field "x" is unexported but missing PkgPath | lower-case name given to StructOf | use exported names |
The Value method matrix Good to know
In plain words: Most Value methods are legal for only a few kinds; the other kinds panic. This table is the quick lookup for "can I call this here".
Common misunderstanding: "Len works on everything countable." It works on Array, Chan, Map, Slice, String and a pointer to an array; calling it on a struct panics with reflect: call of reflect.Value.Len on struct Value.
Definition: per the package documentation each method lists its allowed kinds; the table summarises the common ones.
Choosing the method for a Value v
1 switch v.Kind() {
2 case reflect.Struct: for i := range v.NumField() { ... v.Field(i) ... }
3 case reflect.Slice, reflect.Array: for i := range v.Len() { v.Index(i) }
4 case reflect.Map: it := v.MapRange(); for it.Next() { it.Key(); it.Value() }
5 case reflect.Pointer, reflect.Interface: if !v.IsNil() { recurse(v.Elem()) }
6 default: v.Int() / v.String() / v.Bool() / v.Float() by kind
7 }Real scenario: every recursive walker in this chapter (Flatten, encode, the validator's size) is this switch; a walker that forgets the Pointer case panics on the first *T field.
| Method | Legal kinds | Panics otherwise with |
|---|---|---|
Len() | Array, Chan, Map, Slice, String, pointer to Array | call of reflect.Value.Len on K Value |
Index(i) | Array, Slice, String | same pattern |
MapKeys, MapIndex, MapRange | Map | same pattern |
Field, NumField, FieldByName | Struct | same pattern |
Elem() | Interface, Pointer | same pattern |
IsNil() | Chan, Func, Interface, Map, Pointer, Slice | same pattern |
Int() | Int ... Int64 | same pattern |
Call | Func | same pattern |
IsZero() | any valid Value | panics on invalid |
IsValid() | any, including the zero Value | never |
Solving the classic problems
A struct validator driven by tags
Parse validate:"required,min=2" once per reflect.Type, cache the plan in a sync.Map, then walk fields by index. Programmer errors in tags (an unknown rule, a bad number) are returned as plain errors and cached; data violations come back as Errors.
| Solution | How | Advantage | Cost |
|---|---|---|---|
| Reflective validator with a plan cache | parse tags once, walk Index paths | one function validates every form type | tag typos are run-time errors |
| Generated validators | go generate from tags or schema | typed, fast, checked at build | build step |
Explicit Validate() methods | hand-written per type | clearest to read and test | repetitive |
// Package validate is a mini struct validator driven by `validate:"..."` tags.
// The tag is parsed once per type and cached; validation only walks the plan.
package validate
import (
"errors"
"fmt"
"reflect"
"strconv"
"strings"
"sync"
)
type rule struct {
name string
arg int
}
type fieldPlan struct {
index []int
name string
rules []rule
}
// plans caches the parsed plan per reflect.Type (the "type cache").
var plans sync.Map // map[reflect.Type]*[]fieldPlan or error
// FieldError is one violation.
type FieldError struct {
Field string
Rule string
Msg string
}
func (e FieldError) Error() string { return e.Field + ": " + e.Msg }
// Errors is the aggregate returned by Struct.
type Errors []FieldError
func (e Errors) Error() string {
parts := make([]string, len(e))
for i, fe := range e {
parts[i] = fe.Error()
}
return strings.Join(parts, "; ")
}
// ErrNotStruct is returned when the argument is not a struct or pointer to one.
var ErrNotStruct = errors.New("validate: argument must be a struct or a non-nil pointer to a struct")
func plan(t reflect.Type) ([]fieldPlan, error) {
if cached, ok := plans.Load(t); ok {
if err, isErr := cached.(error); isErr {
return nil, err
}
return cached.([]fieldPlan), nil
}
var out []fieldPlan
for i := 0; i < t.NumField(); i++ {
sf := t.Field(i)
if !sf.IsExported() {
continue
}
tag, ok := sf.Tag.Lookup("validate")
if !ok || tag == "-" {
continue
}
fp := fieldPlan{index: sf.Index, name: sf.Name}
for _, part := range strings.Split(tag, ",") {
name, arg, hasArg := strings.Cut(part, "=")
r := rule{name: name}
if hasArg {
n, err := strconv.Atoi(arg)
if err != nil {
err = fmt.Errorf("validate: %s.%s: bad argument in %q: %w", t, sf.Name, part, err)
plans.Store(t, err)
return nil, err
}
r.arg = n
}
switch name {
case "required", "min", "max":
default:
err := fmt.Errorf("validate: %s.%s: unknown rule %q", t, sf.Name, name)
plans.Store(t, err)
return nil, err
}
fp.rules = append(fp.rules, r)
}
out = append(out, fp)
}
plans.Store(t, out)
return out, nil
}
// Struct validates v. A programmer error in a tag (unknown rule, bad number)
// is returned as a plain error; data violations are returned as Errors.
func Struct(v any) error {
rv := reflect.ValueOf(v)
if rv.Kind() == reflect.Pointer {
if rv.IsNil() {
return ErrNotStruct
}
rv = rv.Elem()
}
if rv.Kind() != reflect.Struct {
return ErrNotStruct
}
fps, err := plan(rv.Type())
if err != nil {
return err
}
var errs Errors
for _, fp := range fps {
f := rv.FieldByIndex(fp.index)
for _, r := range fp.rules {
if msg := check(f, r); msg != "" {
errs = append(errs, FieldError{Field: fp.name, Rule: r.name, Msg: msg})
if r.name == "required" {
break // an empty value would also fail every later rule
}
}
}
}
if len(errs) > 0 {
return errs
}
return nil
}
func check(f reflect.Value, r rule) string {
switch r.name {
case "required":
if f.IsZero() {
return "is required"
}
case "min":
if n, ok := size(f); !ok {
return "min is not valid for kind " + f.Kind().String()
} else if n < r.arg {
return fmt.Sprintf("must be at least %d", r.arg)
}
case "max":
if n, ok := size(f); !ok {
return "max is not valid for kind " + f.Kind().String()
} else if n > r.arg {
return fmt.Sprintf("must be at most %d", r.arg)
}
}
return ""
}
// size gives the number a min/max rule compares: the value for integers, the
// rune count for strings, the length for slices and maps.
func size(f reflect.Value) (int, bool) {
switch f.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return int(f.Int()), true
case reflect.String:
return len([]rune(f.String())), true
case reflect.Slice, reflect.Map:
return f.Len(), true
}
return 0, false
}The tests include a concurrent run under -race because the cache is shared; the rule required short-circuits the other rules of the same field so an empty name reports one message, not three.
A mini JSON-like encoder
The same walk as encoding/json for the common kinds: recursion on Kind, struct tags with omitempty and -, sorted map keys, pointers and interfaces unwrapped, ErrUnsupported for channels and functions, and a depth limit as a cycle guard. A test asserts byte equality with encoding/json on a mixed document, so the model is checked against the real codec rather than against opinion.
// Package miniencode is a tiny JSON-like encoder written with reflect. It is a
// teaching model of encoding/json: struct tags, omitempty, maps with sorted
// keys, slices, pointers and interfaces, and cycle protection.
package miniencode
import (
"errors"
"fmt"
"reflect"
"sort"
"strconv"
"strings"
)
// ErrUnsupported is returned for kinds with no JSON form (chan, func, complex).
var ErrUnsupported = errors.New("miniencode: unsupported type")
// ErrDepth is returned when nesting exceeds maxDepth (a cheap cycle guard).
var ErrDepth = errors.New("miniencode: nesting too deep (cycle?)")
const maxDepth = 32
// Marshal encodes v.
func Marshal(v any) (string, error) {
var sb strings.Builder
if err := encode(&sb, reflect.ValueOf(v), 0); err != nil {
return "", err
}
return sb.String(), nil
}
func encode(sb *strings.Builder, v reflect.Value, depth int) error {
if depth > maxDepth {
return ErrDepth
}
if !v.IsValid() {
sb.WriteString("null")
return nil
}
switch v.Kind() {
case reflect.Bool:
sb.WriteString(strconv.FormatBool(v.Bool()))
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
sb.WriteString(strconv.FormatInt(v.Int(), 10))
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
sb.WriteString(strconv.FormatUint(v.Uint(), 10))
case reflect.Float32, reflect.Float64:
sb.WriteString(strconv.FormatFloat(v.Float(), 'g', -1, v.Type().Bits()))
case reflect.String:
sb.WriteString(strconv.Quote(v.String()))
case reflect.Pointer, reflect.Interface:
if v.IsNil() {
sb.WriteString("null")
return nil
}
return encode(sb, v.Elem(), depth+1)
case reflect.Slice, reflect.Array:
if v.Kind() == reflect.Slice && v.IsNil() {
sb.WriteString("null")
return nil
}
sb.WriteByte('[')
for i := 0; i < v.Len(); i++ {
if i > 0 {
sb.WriteByte(',')
}
if err := encode(sb, v.Index(i), depth+1); err != nil {
return err
}
}
sb.WriteByte(']')
case reflect.Map:
if v.Type().Key().Kind() != reflect.String {
return fmt.Errorf("%w: map key %s", ErrUnsupported, v.Type().Key())
}
if v.IsNil() {
sb.WriteString("null")
return nil
}
keys := v.MapKeys()
sort.Slice(keys, func(i, j int) bool { return keys[i].String() < keys[j].String() })
sb.WriteByte('{')
for i, k := range keys {
if i > 0 {
sb.WriteByte(',')
}
sb.WriteString(strconv.Quote(k.String()))
sb.WriteByte(':')
if err := encode(sb, v.MapIndex(k), depth+1); err != nil {
return err
}
}
sb.WriteByte('}')
case reflect.Struct:
return encodeStruct(sb, v, depth)
default:
return fmt.Errorf("%w: %s", ErrUnsupported, v.Type())
}
return nil
}
func encodeStruct(sb *strings.Builder, v reflect.Value, depth int) error {
sb.WriteByte('{')
first := true
t := v.Type()
for i := 0; i < t.NumField(); i++ {
sf := t.Field(i)
if !sf.IsExported() {
continue
}
name, opts, _ := strings.Cut(sf.Tag.Get("json"), ",")
if name == "-" && opts == "" {
continue
}
if name == "" {
name = sf.Name
}
fv := v.Field(i)
if opts == "omitempty" && isEmpty(fv) {
continue
}
if !first {
sb.WriteByte(',')
}
first = false
sb.WriteString(strconv.Quote(name))
sb.WriteByte(':')
if err := encode(sb, fv, depth+1); err != nil {
return fmt.Errorf("field %s: %w", sf.Name, err)
}
}
sb.WriteByte('}')
return nil
}
// isEmpty mirrors encoding/json's omitempty set.
func isEmpty(v reflect.Value) bool {
switch v.Kind() {
case reflect.Array, reflect.Map, reflect.Slice, reflect.String:
return v.Len() == 0
case reflect.Bool, reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64,
reflect.Float32, reflect.Float64, reflect.Interface, reflect.Pointer:
return v.IsZero()
}
return false
}encoding/json feature | In miniencode | Missing on purpose |
|---|---|---|
Tag name, omitempty, - | yes | string, omitzero options |
| Sorted map keys | yes (string keys only) | integer keys, TextMarshaler keys |
| Pointers, interfaces | yes | Marshaler and TextMarshaler hooks |
| Cycle protection | depth limit of 32 | the real codec detects cycles and returns json: unsupported value: encountered a cycle via *main.N |
HTML escaping, float formatting rules | no | many details of strconv use |
| Encoder cache per type | no | encoding/json caches per Type |
An environment-to-struct loader
Tags env:"PORT" default:"8080" required:"true" describe a configuration; Load(&cfg, os.LookupEnv) fills it. The loader recurses into nested structs, special-cases time.Duration by Type before it looks at Kind, collects every problem with errors.Join, and takes a lookup function so tests pass a map instead of touching the process environment. For flag and environment precedence at the program level see CLI Flags, Subcommands, Environment Variables & Logging (log/slog).
// Package envload fills a struct from environment variables using `env` and
// `default` tags, the pattern behind envconfig and caarlos0/env.
package envload
import (
"errors"
"fmt"
"reflect"
"strconv"
"strings"
"time"
)
// Lookup has the shape of os.LookupEnv, so tests can pass a map instead.
type Lookup func(key string) (string, bool)
var durationType = reflect.TypeFor[time.Duration]()
// Load fills dst, which must be a non-nil pointer to a struct. Every problem
// is collected and returned together with errors.Join.
func Load(dst any, lookup Lookup) error {
rv := reflect.ValueOf(dst)
if rv.Kind() != reflect.Pointer || rv.IsNil() || rv.Elem().Kind() != reflect.Struct {
return fmt.Errorf("envload: dst must be a non-nil pointer to struct, got %T", dst)
}
var errs []error
load(rv.Elem(), lookup, &errs)
return errors.Join(errs...)
}
func load(sv reflect.Value, lookup Lookup, errs *[]error) {
st := sv.Type()
for i := 0; i < st.NumField(); i++ {
sf := st.Field(i)
fv := sv.Field(i)
if !sf.IsExported() {
continue
}
if sf.Type.Kind() == reflect.Struct && sf.Type != durationType {
load(fv, lookup, errs) // nested struct: recurse
continue
}
key, ok := sf.Tag.Lookup("env")
if !ok {
continue
}
raw, found := lookup(key)
if !found || raw == "" {
def, hasDef := sf.Tag.Lookup("default")
switch {
case hasDef:
raw = def
case sf.Tag.Get("required") == "true":
*errs = append(*errs, fmt.Errorf("envload: %s is required (field %s)", key, sf.Name))
continue
default:
continue
}
}
if err := set(fv, raw); err != nil {
*errs = append(*errs, fmt.Errorf("envload: %s (field %s): %w", key, sf.Name, err))
}
}
}
func set(fv reflect.Value, raw string) error {
if fv.Type() == durationType {
d, err := time.ParseDuration(raw)
if err != nil {
return err
}
fv.SetInt(int64(d))
return nil
}
switch fv.Kind() {
case reflect.String:
fv.SetString(raw)
case reflect.Bool:
b, err := strconv.ParseBool(raw)
if err != nil {
return err
}
fv.SetBool(b)
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
n, err := strconv.ParseInt(raw, 10, fv.Type().Bits())
if err != nil {
return err
}
fv.SetInt(n)
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
n, err := strconv.ParseUint(raw, 10, fv.Type().Bits())
if err != nil {
return err
}
fv.SetUint(n)
case reflect.Float32, reflect.Float64:
f, err := strconv.ParseFloat(raw, fv.Type().Bits())
if err != nil {
return err
}
fv.SetFloat(f)
case reflect.Slice:
if fv.Type().Elem().Kind() != reflect.String {
return fmt.Errorf("unsupported slice of %s", fv.Type().Elem())
}
parts := strings.Split(raw, ",")
s := reflect.MakeSlice(fv.Type(), len(parts), len(parts))
for i, p := range parts {
s.Index(i).SetString(strings.TrimSpace(p))
}
fv.Set(s)
default:
return fmt.Errorf("unsupported kind %s", fv.Kind())
}
return nil
}Scanning rows into structs (sqlx and pgx style)
A query returns column names; a struct has db tags. The scanner builds column -> index path once per type, then for each row hands the driver a []any of pointers into the struct fields (Field(i).Addr().Interface()). Embedded structs are promoted by walking Anonymous fields. A column with no field is an error (sqlx reports missing destination name x in *T), unexported fields are invisible, and All[T] keeps reflection inside the package while callers get []T back. The database side of this is in database/sql & pgx.
// Package scan maps result-set columns to struct fields the way sqlx and pgx's
// RowToStructByName do: read `db` tags once per type, cache the column ->
// field-index map, and hand the driver pointers to the fields.
package scan
import (
"fmt"
"reflect"
"strings"
"sync"
)
// Rows is the subset of *sql.Rows this package needs; a test double satisfies it.
type Rows interface {
Columns() ([]string, error)
Next() bool
Scan(dest ...any) error
Err() error
}
// mapping is column name -> field index path (a path, for embedded structs).
type mapping map[string][]int
var cache sync.Map // reflect.Type -> mapping
func mappingFor(t reflect.Type) mapping {
if m, ok := cache.Load(t); ok {
return m.(mapping)
}
m := mapping{}
var walk func(t reflect.Type, prefix []int)
walk = func(t reflect.Type, prefix []int) {
for i := 0; i < t.NumField(); i++ {
sf := t.Field(i)
idx := append(append([]int(nil), prefix...), i)
if sf.Anonymous && sf.Type.Kind() == reflect.Struct {
walk(sf.Type, idx) // embedded struct: promote its columns
continue
}
if !sf.IsExported() {
continue
}
name := sf.Tag.Get("db")
if name == "-" {
continue
}
if name == "" {
name = strings.ToLower(sf.Name)
}
m[name] = idx
}
}
walk(t, nil)
actual, _ := cache.LoadOrStore(t, m)
return actual.(mapping)
}
// Targets returns one pointer per column, each pointing into dst. A column that
// has no field is an error, as sqlx reports "missing destination name".
func Targets(dst any, cols []string) ([]any, error) {
rv := reflect.ValueOf(dst)
if rv.Kind() != reflect.Pointer || rv.IsNil() || rv.Elem().Kind() != reflect.Struct {
return nil, fmt.Errorf("scan: dst must be a non-nil pointer to struct, got %T", dst)
}
rv = rv.Elem()
m := mappingFor(rv.Type())
out := make([]any, len(cols))
for i, c := range cols {
idx, ok := m[c]
if !ok {
return nil, fmt.Errorf("scan: missing destination name %q in %s", c, rv.Type())
}
out[i] = rv.FieldByIndex(idx).Addr().Interface()
}
return out, nil
}
// All scans every row into a []T. The element type is a type parameter, so the
// caller gets a typed slice back and reflect stays inside the package.
func All[T any](rows Rows) ([]T, error) {
cols, err := rows.Columns()
if err != nil {
return nil, err
}
var out []T
for rows.Next() {
var item T
targets, err := Targets(&item, cols)
if err != nil {
return nil, err
}
if err := rows.Scan(targets...); err != nil {
return nil, err
}
out = append(out, item)
}
return out, rows.Err()
}Safe dynamic dispatch
Use dyncall.Registry or a plain map[string]func(...); never MethodByName on a request value. When you do need method discovery (RPC-style registries, command consoles for operators), filter by signature at registration time and keep the registry read-only afterwards.
Test helpers
Use cmp.Diff with explicit options for domain objects, reflect.DeepEqual for plain data, and errors.Is/errors.As for errors; see Testing & Benchmarking: Table-Driven Tests, Subtests, Coverage, httptest. A test that compares structs with time.Time or nil-versus-empty collections should say which equality it means.
Troubleshooting table
| Symptom | Likely cause | Check |
|---|---|---|
panic: reflect: reflect.Value.SetX using unaddressable value | ValueOf(x) instead of ValueOf(&x).Elem() | pass a pointer |
cannot return value obtained from unexported field | Interface() on a private field | CanInterface() or skip !IsExported() |
| Field is "missing" in output | lower-case name | export it, or add a custom marshaller |
| Tag option ignored | typo or missing quotes | go vet (structtag) and Tag.Lookup |
NumField of non-struct type *T | forgot Elem() | Indirect first |
| Test shows identical values but fails | nil versus empty, time zone, unexported field | cmp.Diff |
| Latency grows with request rate | per-request lookups and tag parsing | cache a plan per Type |
| Race detector reports the cache | map without a lock | sync.Map or build once and publish |
Choosing
| Situation | Recommended | Extra technique | Reason |
|---|---|---|---|
| Encode, decode, print arbitrary user types | reflect in a library | per-type plan cache | the types are unknown by definition |
| Same algorithm over known types | generics | constraints from cmp.Ordered or your own | checked at compile time |
| Known set of types, per-type behaviour | type switch or interface | go generate for boilerplate | simplest, fastest |
| Validation of request DTOs | tag-driven validator | explicit Validate() for cross-field rules | tags suit local rules only |
| Config from environment or files | tag-driven loader | errors collected with errors.Join | one place for defaults |
| DB rows to structs | sqlx-style scan or pgx.RowToStructByName | sqlc for fully typed queries | tag map cached per type |
| Test comparisons | cmp.Diff with options | reflect.DeepEqual for plain data | readable failures |
| Call methods by name from input | registry map | signature filter at registration | no MethodByName on untrusted names |
| Hot loop over a fixed type | direct code | benchmark before and after | reflection is about 5 to 100 times slower per operation here |
| Peek at private fields | do not | export an accessor | unsafe voids memory-safety guarantees |
In architecture: from a single process to a distributed system
Monolith: one process, one database
Reflection is mostly invisible: encoding/json, fmt, a validator and a row scanner use it for you. The simplest correct usage is to depend on libraries that already cache per type, keep DTO structs small with explicit tags, and write no reflection of your own until a library cannot express the need. A startup self-check that calls the validator on every DTO with a zero value turns tag typos into start-up failures instead of request failures.
Modular monolith and multiple databases
Modules exchange DTOs defined in a shared package, so tag names are a contract: renaming a field must not rename a column or a JSON key, which is why tags are written explicitly. One shared validation and scan package (the only place that imports reflect) keeps the rest of the code typed. Each module registers its own types into a registry at start-up rather than discovering them by scanning packages, because Go cannot enumerate the types of a package at run time.
Microservices
Reflection never crosses a service boundary: what crosses is bytes in a schema. A struct that is a JSON contract needs stable tags and a compatibility policy; a Protobuf contract needs generated code (see gRPC & Protobuf in Go), which exists exactly to avoid per-message reflection. Service-local concerns that use reflection: request decoding and validation at the edge, config loading at start-up, row scanning at the repository.
POST /orders (service A)
1 decode: json.Decoder -> reflect over CreateOrder cached per type
2 validate: validator -> tags -> plan per type cached per type
3 persist: scan/args -> reflect over Order cached per type
4 publish: json.Marshal(OrderCreated) -> broker -> service B
5 service B repeats 1 and 2 for its own struct, never sees A's Go typesDistributed data: replicas, caches, NAT and containers
A cache stores bytes, not types; reflection decodes them on read. If a cached value was written by an older binary, a new struct may have fewer or more fields: decoding is tolerant only if the codec is (JSON ignores unknown keys by default, gob matches by field name). Never use a type name as a cache key to select a decoder without an allow-list. In containers and sidecars nothing changes for reflect itself, but memory limits make per-request allocation visible: a reflective path that allocates per field can double garbage-collection frequency under load.
Scaling path: 1×, 10×, 100×
| Load | Concern | Action |
|---|---|---|
| 1× | Correct panics-to-errors translation | tests with odd types: pointers to pointers, nil, embedded, unexported |
| 10× | Allocation and tag parsing visible in profiles | cache a plan per Type; prefer index paths; pprof allocation profile |
| 100× | Codec and scanner CPU dominate | generated code (sqlc, easyjson, Protobuf) for the few hottest types, keep reflection for the long tail |
-- The table a row scanner fills. The column names are the contract between the
-- database and the `db` tags: renaming a column without renaming the tag
-- fails at run time with "missing destination name", not at compile time.
CREATE TABLE users (
id bigint PRIMARY KEY,
name text NOT NULL,
email text,
created_by text NOT NULL DEFAULT 'system'
);
SELECT id, name, email, created_by FROM users WHERE id = $1;Go
Example
A small, safe, cached helper wraps all the reflection; callers stay typed. The snippet is the whole module's demo, which exercises every package:
// Command demo prints the outputs quoted in the lab.
package main
import (
"fmt"
"os"
"reflect"
"sort"
"strings"
"academy/reflect/deepeq"
"academy/reflect/dyncall"
"academy/reflect/envload"
"academy/reflect/fields"
"academy/reflect/laws"
"academy/reflect/maker"
"academy/reflect/miniencode"
"academy/reflect/validate"
)
type signup struct {
Name string `validate:"required,min=2,max=8"`
Age int `validate:"min=18"`
Tags []string `validate:"max=2"`
}
type config struct {
Port int `env:"PORT" default:"8080"`
Debug bool `env:"DEBUG"`
Hosts []string `env:"HOSTS"`
DBURL string `env:"DB_URL" required:"true"`
Timeout string `env:"TIMEOUT" default:"5s"`
}
func main() {
fmt.Println("-- laws")
fmt.Println(laws.Describe(laws.Celsius(21.5)))
d, p, r := laws.SetThroughValue()
fmt.Println("CanSet direct:", d, "via pointer:", p, "x now:", r)
fmt.Println(laws.UnaddressableSet())
fmt.Println(laws.UnexportedSet())
fmt.Println(laws.WrongKind())
fmt.Println(laws.ElemOnStruct())
fmt.Println("-- fields")
for _, in := range fields.Walk(&fields.User{}) {
fmt.Printf("%-8s %-16s %-7s exported=%-5v canSet=%-5v canInterface=%v\n", in.Name, in.Type, in.Kind, in.Exported, in.CanSet, in.CanIface)
}
fmt.Println(strings.Join(fields.Flatten(fields.User{ID: 7, Name: "Ada", Address: fields.Address{City: "Tehran"}, Tags: []string{"a", "b"}}), " "))
fmt.Println("-- validate")
fmt.Println(validate.Struct(signup{Name: "A", Age: 3, Tags: []string{"x", "y", "z"}}))
fmt.Println(validate.Struct(signup{Age: 20}))
fmt.Println("-- miniencode")
s, _ := miniencode.Marshal(map[string]any{"b": []int{1, 2}, "a": struct {
N string `json:"n,omitempty"`
M int
}{M: 2}})
fmt.Println(s)
fmt.Println("-- envload")
var c config
err := envload.Load(&c, func(k string) (string, bool) {
v, ok := map[string]string{"PORT": "eighty", "HOSTS": "a,b"}[k]
return v, ok
})
fmt.Println(err)
_ = os.Stdout
fmt.Println("-- dyncall")
out, err := dyncall.Invoke(dyncall.Calculator{Offset: 1}, "Add", 2, 3)
fmt.Println(out, err)
_, err = dyncall.Invoke(dyncall.Calculator{}, "Div", 1, 0)
fmt.Println(err)
_, err = dyncall.Invoke(dyncall.Calculator{}, "Exec", "rm")
fmt.Println(err)
fmt.Println(dyncall.Methods(dyncall.Calculator{}), dyncall.Methods(&dyncall.Calculator{}))
fmt.Println("-- maker")
rel := maker.Relations()
keys := make([]string, 0, len(rel))
for k := range rel {
keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
fmt.Printf("%-28s %v\n", k, rel[k])
}
v, _ := maker.DynamicStruct(map[string]reflect.Type{"Name": reflect.TypeFor[string](), "Age": reflect.TypeFor[int]()}, []string{"Name", "Age"})
fmt.Printf("%T\n", v)
fmt.Println("-- deepeq")
cases := deepeq.Cases()
names := make([]string, 0, len(cases))
for k := range cases {
names = append(names, k)
}
sort.Strings(names)
for _, k := range names {
fmt.Printf("%-32s %v\n", k, cases[k])
}
fmt.Print(deepeq.Diff(deepeq.Order{ID: 1, Items: []string{"a"}}, deepeq.Order{ID: 2, Items: []string{"a"}}))
}The Go angle
Go keeps reflect deliberately explicit: no annotations, no hidden proxies, no runtime type registry, no way to enumerate the types of a package. Reflection works on values handed to it, and every library built on it either caches per Type or pays per call. Interfaces and generics (see Interfaces, Type Assertions, Type Switches & any and Generics) are the first tools; go generate is the second; reflect is the third, kept behind a small package that returns errors instead of panics. The JSON codec that depends on it most is in JSON, XML, Struct Tags, Encoder/Decoder, Base64, and the memory model underneath Elem and addressability starts in Pointers & Memory Model Basics.
For PHP/Laravel developers
| PHP | Go | Note |
|---|---|---|
new ReflectionClass($obj) | reflect.TypeOf(x) | PHP reflects classes by name; Go reflects the type of a value |
getProperties() | NumField(), Field(i) | Go has no private toggle; a lower-case name is closed to reflection |
ReflectionProperty::setAccessible(true) | none | not needed since PHP 8.1; Go has no equivalent without unsafe |
$property->setValue($obj, $v) | Elem().Field(i).Set(...) | Go requires a pointer for settability |
getAttributes(), #[Route('/x')] | struct tags, read with Tag.Get | PHP attributes are typed classes; Go tags are untyped strings |
ReflectionMethod::invoke | MethodByName(...).Call(...) | Go panics on a wrong argument; PHP throws |
ReflectionNamedType | reflect.Type | getName() is Name()/String() |
class_exists($name), new $name | no equivalent | Go cannot make a type from a string; use a registry map |
| Laravel container auto-wiring by type hints | wire (codegen) or a manual constructor | Laravel reads constructor types with ReflectionClass per resolve; Go prefers explicit wiring |
$class = new ReflectionClass(User::class);
foreach ($class->getProperties() as $p) {
foreach ($p->getAttributes(Column::class) as $attr) {
echo $p->getName(), ' => ', $attr->newInstance()->name, "\n";
}
}The Go version of this loop is the walk from Walking a struct with sf.Tag.Lookup("db"). PHP reflection is a first-class, class-based API; Go's is a small, value-based one that you are expected to avoid.
Lab
All outputs below come from running the module on the host with Go 1.27.4 (the module declares go 1.24); nothing needs Docker or a network, except the first go mod tidy that fetched go-cmp. Run from docs/snippets/go/reflect/go (export PATH=/opt/homebrew/bin:$PATH on this machine).
- Run the demo:
go run ./demo. Real output (excerpt, the full run prints about 70 lines):
-- laws
type=laws.Celsius kind=float64 value=21.5
CanSet direct: false via pointer: true x now: 7.1
reflect: reflect.Value.SetString using unaddressable value
reflect: reflect.Value.SetInt using value obtained using unexported field
reflect: call of reflect.Value.SetString on int Value
reflect: call of reflect.Value.Elem on struct Value
-- fields
ID int64 int64 exported=true canSet=true canInterface=true
secret string string exported=false canSet=false canInterface=false
Address fields.Address struct exported=true canSet=true canInterface=true
ID=7 Name=Ada Email= Skipped= City=Tehran Zip= Tags=[a,b]
-- validate
Name: must be at least 2; Age: must be at least 18; Tags: must be at most 2
Name: is required
-- miniencode
{"a":{"M":2},"b":[1,2]}
-- envload
envload: PORT (field Port): strconv.ParseInt: parsing "eighty": invalid syntax
envload: DB_URL is required (field DBURL)- Second part of the same run (excerpt):
-- dyncall
[6] <nil>
division by zero
dyncall: dyncall.Calculator has no exported method "Exec"
[Add Boom Div Sum] [Add Boom Div Reset Sum]
-- maker
*Handle implements Stringer true
Handle implements Stringer false
ID assignable to Stringer true
ID assignable to int false
ID convertible to int true
ID implements Stringer true
[]int comparable false
string comparable true
*struct { Name string "json:\"name\""; Age int "json:\"age\"" }
-- deepeq
NaN vs NaN false
func vs same func false
int vs int64 (different type) false
nil map vs empty map false
nil slice vs empty slice false
same pointer to NaN true
time same instant, other zone false
unexported fields differ false
deepeq.Order{
- ID: 1,
+ ID: 2,
Items: {"a"},
Meta: nil,
... // 1 ignored field
}- Run the tests with the race detector:
go test -race -count=1 ./.... Real output (times removed, they vary):
ok academy/reflect/bench [no tests to run]
ok academy/reflect/deepeq
? academy/reflect/demo [no test files]
ok academy/reflect/dyncall
ok academy/reflect/envload
ok academy/reflect/fields
ok academy/reflect/laws
ok academy/reflect/maker
ok academy/reflect/miniencode
ok academy/reflect/scan
ok academy/reflect/validate- Run the benchmarks:
go test -bench . -benchmem -run xxx ./bench. Real output on one Apple M4 Pro; your numbers will differ, the ranking will not:
BenchmarkDirect-12 1000000000 0.2485 ns/op 0 B/op 0 allocs/op
BenchmarkReflectByIndex-12 889300878 1.356 ns/op 0 B/op 0 allocs/op
BenchmarkReflectByName-12 49951953 24.34 ns/op 0 B/op 0 allocs/op
BenchmarkTagLookupEveryTime-12 15499520 77.85 ns/op 0 B/op 0 allocs/op
BenchmarkTagFromCache-12 1000000000 1.029 ns/op 0 B/op 0 allocs/op
BenchmarkInterfaceAlloc-12 100000000 11.13 ns/op 16 B/op 1 allocs/op- Make
go vetcomplain: add a fieldA stringwith the tag`json:name`to any struct and rungo vet ./.... Real output of the same mistake in a scratch file:struct field tag `json:name` not compatible with reflect.StructTag.Get: bad syntax for struct tag value. Then callreflect.ValueOf("x").SetString("y")and rungo vet: no warning;go runpanics with the text from the first step. - Break the validator: add
validate:"emial"to a field and callvalidate.Struct. Real result in the test:validate: validate.unknown.A: unknown rule "emial"(the plan error is cached, so the second call returns the same error without re-parsing). - Reproduce a production mix-up: in
deepeqchangeCasesto compare[]int(nil)with[]int{}undercmpopts.EquateEmpty()and watchcmp.Equalsay true whilereflect.DeepEqualsays false. Expected, not run here as a separate command; theDifftest covers the same rule. - Point the scanner at a real database with
database/sqland a driver, mapSELECT id, name, email, created_by FROM usersinto[]Userwithscan.All. Expected, not run: it needs a PostgreSQL server; the fake rows inscan_test.gostand in for it.
Common misconceptions
| Belief | Reality |
|---|---|
reflect.ValueOf(x).SetInt(5) changes x | ValueOf(x) copies; use ValueOf(&x).Elem() |
Kind and Type are the same | a type ID int has Kind int and Type ID |
| Reflection can read and write private fields | Interface() and Set* panic on them; unsafe is the only way and it voids safety |
Tag.Get returning "" means no tag | it may be present and empty; use Tag.Lookup |
DeepEqual is == for big values | nil differs from empty, NaN never equals, funcs never equal, unexported fields count |
cmp.Equal is DeepEqual but faster | it is stricter and more informative; it panics on unexported fields by default |
| Reflection always allocates | getters and setters on a held Value do not; boxing with Interface() does |
ValueOf always forces the argument onto the heap | not since Go 1.21 |
| Generics replace reflection | they cannot see fields or tags; they replace it for type-uniform algorithms |
go vet finds reflect misuse | it checks tag syntax only; unaddressable sets are found by tests |
MethodByName sees all methods | exported ones in the method set of the exact type; pointer-receiver methods need a pointer |
StructOf can build a type with methods | it builds anonymous structs with exported fields only |
| I can look up a type by its name string | there is no such function; build a registry |
| Reflection is safe on untrusted names | MethodByName(input) runs any exported method; use an allow-list |
reflect.Ptr is gone | it is an alias of reflect.Pointer |
Cheat sheet
| Topic | Remember |
|---|---|
| Entry points | reflect.TypeOf(x), reflect.ValueOf(x), reflect.TypeFor[T]() (Go 1.22) |
| Back to a value | v.Interface().(T) or reflect.TypeAssert[T](v) (Go 1.25) |
| Settable | reflect.ValueOf(&x).Elem(); check CanSet() |
| Kind versus Type | switch on Kind for families; compare Type for exact types |
| Nil guards | IsValid() after Elem()/FieldByName, IsNil() before Elem() on pointers |
| Struct walk | NumField, Field(i), IsExported(), Tag.Lookup, Index paths |
| Unexported | readable by kind getters, never by Interface() or Set* |
| Calling | MethodByName(n).Call(args); check arity and AssignableTo first |
| Make | New, MakeSlice, MakeMap, SliceOf, MapOf, StructOf (exported fields only) |
| Relations | Implements (check *T too), AssignableTo, ConvertibleTo, Comparable |
| DeepEqual | nil slice is not empty slice; NaN and funcs are never equal; unexported fields count |
| go-cmp | cmp.Diff(want, got, opts...); tests only; IgnoreUnexported, EquateEmpty |
| Cost | cache a plan per reflect.Type; resolve names to index paths once |
| Alternatives | interface, generics, go generate, in that order |
| Security | allow-list instead of MethodByName(input); bind into DTOs |
| Panic texts | start with reflect:; read method, kind and the word unaddressable or unexported |
| Library users | encoding/json, fmt, text/template, database/sql scanners, validators, DI containers |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — x := 3.4; v := reflect.ValueOf(x); v.SetFloat(7.1) panics. What is the exact text, and what is the one-line fix? Important
Answer
Answer: panic: reflect: reflect.Value.SetFloat using unaddressable value. ValueOf(x) holds a copy. Use reflect.ValueOf(&x).Elem().SetFloat(7.1), where Elem() reaches the variable itself and CanSet() is true.
2 — type Celsius float64. What are TypeOf(Celsius(1)).Kind() and TypeOf(Celsius(1)) == TypeOf(float64(1))? Must-know
Answer
Answer: float64 and false. The Kind is the underlying category; the Type is the named type, so the two Type values differ.
3 — A struct has a lower-case field secret int. Which of Type().Field(i), Value.Field(i).Int(), Value.Field(i).Interface() and Value.Field(i).SetInt(1) work? Important
Answer
Answer: The first two work (description and kind-specific read). Interface() panics with cannot return value obtained from unexported field or method; SetInt panics with using value obtained using unexported field.
4 — When must you use Tag.Lookup instead of Tag.Get? Important
Answer
Answer: When an absent key and a present key with an empty value mean different things. Get returns "" for both; Lookup returns (value, ok).
5 — reflect.DeepEqual([]int(nil), []int{}) and reflect.DeepEqual(math.NaN(), math.NaN()): results and why? Important
Answer
Answer: Both false. A non-nil empty slice differs from a nil slice by definition, and NaN is not equal to itself under ==, which DeepEqual relaxes only for pointers, slices and maps that are the same object.
6 — Why does reflect.TypeFor[Handle]().Implements(stringerType) return false while reflect.TypeFor[*Handle]() returns true when String has a pointer receiver? Important
Answer
Answer: The method set of Handle excludes pointer-receiver methods; the method set of *Handle includes them. Check both when you look for an interface such as Marshaler.
7 — A service does reflect.ValueOf(svc).MethodByName(r.URL.Query().Get("cmd")).Call(nil). What is wrong and what replaces it? Must-know
Answer
Answer: The client picks which exported method runs: remote code execution over your API. Replace it with a registry map built at start-up from a literal list, with argument checking, so unknown names are an error.
8 — What does a type cache key on, and why does it fix most of the cost? Good to know
Answer
Answer: It keys on reflect.Type (comparable, so usable as a map key). The first use parses tags and resolves field index paths; later uses only walk the stored plan, so per-request tag parsing and FieldByName lookups disappear.
9 — Name two situations where generics or go generate are better than reflection and one where they cannot be used. Important
Answer
Answer: Better: the same algorithm over known types (generics), per-type boilerplate such as marshallers or SQL bindings (go generate, sqlc). Not usable: code that must read struct tags or fields of types it was never compiled with, such as encoding/json or a validator.
10 — go vet accepts reflect.ValueOf("x").SetString("y"). What catches it? Important
Answer
Answer: A test that executes the line: it panics with unaddressable value. go vet's structtag check covers tag syntax only; reflect preconditions are checked at run time.
11 — What does StructOf refuse, and what check should you do before calling it with names from a schema? Good to know
Answer
Answer: It panics on unexported field names (field "x" is unexported but missing PkgPath) and cannot add methods. Check token.IsExported(name) (note that StructField.IsExported() is true for hand-built fields with an empty PkgPath).
Glossary
| Term | Meaning |
|---|---|
| reflection | A program inspecting and manipulating its own types and values at run time |
| laws of reflection | The three rules from the Go blog: interface to object, object to interface, settable to modify |
reflect.Type | Interface describing a type: kind, name, fields, methods, element type |
reflect.Value | Struct holding a value plus flags: addressable, read-only, method |
reflect.TypeOf | Returns the Type of the dynamic value in an interface |
reflect.ValueOf | Returns a Value holding a copy of the interface's value |
reflect.TypeFor[T]() | Go 1.22 shortcut for the Type of T, including interface types |
Interface() | Turns a Value back into any; panics for unexported fields |
reflect.TypeAssert | Go 1.25 generic assertion from a Value without an extra allocation |
Kind | The category of a type: Struct, Slice, Pointer, Int, and so on |
Elem() | Follows a pointer or interface; for types, gives the element of a pointer, slice, array, map or chan |
reflect.Pointer | The Kind of pointers; reflect.Ptr is the old alias |
| settable | A Value that can be assigned to: addressable and not from an unexported field |
| addressable | A Value that refers to a variable, not a copy; CanAddr() |
CanSet | Reports whether Set* is legal |
CanInterface | Reports whether Interface() is legal |
IsExported | True for upper-case field or method names (PkgPath empty) |
NumField, Field | Count and access struct fields by index |
FieldByName | Looks a field up by name; costs more than an index |
VisibleFields | All fields reachable by name, including promoted ones |
StructTag | The raw tag string after a field |
Tag.Get | Value of a tag key; empty string when absent or empty |
Tag.Lookup | Value and an ok flag for presence |
SetString, SetInt | Kind-specific setters |
Set | Assigns an assignable Value |
| unaddressable value | The state that makes Set* panic: the Value is a copy |
Convert | Converts a Value like a Go conversion T(x) |
Call | Invokes a function Value with []Value arguments |
MethodByName | Finds an exported method in the method set of the held type |
reflect.New | Allocates a zero value and returns a pointer Value |
MakeSlice, MakeMap | Create slices and maps from a Type |
SliceOf, MapOf | Create slice and map types |
StructOf | Creates an anonymous struct type from exported fields |
MakeFunc | Creates a function Value backed by your func([]Value) []Value |
Implements | Whether a type satisfies an interface type |
AssignableTo, ConvertibleTo | Type-level checks before Set and Convert |
DeepEqual | Recursive equality with special cases for nil, NaN, funcs and unexported fields |
| NaN | Not-a-number; unequal to itself, so DeepEqual of values containing it is false |
go-cmp | github.com/google/go-cmp, a comparison library with options and diffs |
| allocation | A heap allocation; boxing a value with Interface() may cause one |
| type cache | A map from reflect.Type to a precomputed plan |
go generate | Tool that runs generators named in //go:generate comments; output is committed |
| code generation | Producing Go source ahead of time so reflection is not needed at run time |
encoding/json | The standard codec that reflects over struct fields and tags |
| ORM | Object-relational mapper; reflects over structs to build SQL and scan rows |
| validator | A library that checks struct fields against tag rules |
| DI container | A dependency-injection container that reads constructor parameter types |
| untrusted type names | Type or method names from input; never resolve them with reflection, use an allow-list |
sqlx | A library that scans database rows into structs using db tags |
reflectlite | internal/reflectlite, a slim reflect for use inside the standard library |
unsafe | Package that bypasses type and visibility rules; voids safety guarantees |
ReflectionClass | PHP's class-based reflection entry point |
| attributes | PHP 8 typed annotations read via getAttributes(); Go uses struct tags |
zero Value | The invalid Value{}; IsValid() is false and most methods panic |
Seq, Seq2 | Go 1.23 range-style iterators over a Value |
References
- Go blog and release notes: The Laws of Reflection, Generating code, Go 1.17, Go 1.18, Go 1.20, Go 1.21, Go 1.22 (TypeFor), Go 1.23, Go 1.25 (TypeAssert), Go 1.26 (iterators)
- Language and community: The Go Programming Language Specification, Effective Go, Go FAQ, Go Code Review Comments
- Source read for internals: reflect/value.go, sort/slice.go, errors/wrap.go
- Package docs (Go 1.27.4 text read locally with
go doc -all reflect; pkg.go.dev refuses automated clients): reflect, github.com/google/go-cmp/cmp, go-cmp README - Third-party: envconfig
- PHP: Reflection, Attributes overview, ReflectionClass::getAttributes
- Siblings: Interfaces, Type Assertions, Type Switches & any, Structs, Methods, Embedding & Struct Tags, JSON, XML, Struct Tags, Encoder/Decoder, Base64, Generics, Pointers & Memory Model Basics, Errors, Wrapping, Panic, Recover & Defer, Testing & Benchmarking, Mocking with Interfaces, Dependency Injection for Testability, testify, database/sql & pgx, CLI Flags, Subcommands, Environment Variables & Logging (log/slog), Toolchain, Modules & Packages, Project Layout, golangci-lint, Makefile, Docker & Multi-Binary Builds, Strings, Runes, fmt Verbs, text/template & regexp, gRPC & Protobuf in Go