Skip to content

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 forGo to
Tables you can memorise in one minuteEverything in one minute
Why reflection exists and what it costsWhy it exists
The 2011 blog post, Go 1.18 to 1.26 changesWhere it comes from
TypeOf, ValueOf, the first lawLaw 1
Interface(), TypeAssert, the second lawLaw 2
Kind versus Type, named typesKind versus Type
Elem, reflect.Pointer, nil and the zero ValueElem, pointers and nil
CanSet, CanAddr, the third law, unaddressable valueSettability
NumField, Field, FieldByName, VisibleFieldsWalking a struct
StructTag, Tag.Get, Tag.LookupStruct tags
IsExported, CanInterface, unexported fieldsExported and unexported
SetString, SetInt, Set, Convert, SetZeroReading and setting
MakeSlice, MakeMap, MapRange, Append, IndexSlices and maps
Call, MethodByName, variadics, MakeFuncCalling functions
reflect.New, SliceOf, MapOf, StructOf, FuncOfMaking types and values
Implements, AssignableTo, ConvertibleTo, ComparableType relations
DeepEqual, NaN, nil versus empty, unexportedDeepEqual
go-cmp, cmpopts, cmp.Diffgo-cmp
TypeFor, Seq, Fields, version tableVersions
allocations, caching reflect.Type lookupsPerformance
generics, interfaces, go generate insteadAlternatives
encoding/json, fmt, sqlx, pgx, validators, DI containersIn the wild
Reflecting over untrusted type namesSecurity
unsafe, reflectlite, what go vet cannot checkunsafe, reflectlite and vet
Every panic textMechanics
A validator, encoder, env loader, row scannerSolving the classic problems
Reflect or notChoosing
Monolith to distributed systemIn architecture
Reproduce the outputsLab
Wrong beliefs, cheat sheet, every termMisconceptions, Cheat sheet, Glossary

Everything in one minute ​

The three laws (from the Go blog).

LawIn plain wordsCodeFailure when broken
1. Interface value to reflection objectHand any value to TypeOf/ValueOf and you get its type and its valuereflect.TypeOf(x), reflect.ValueOf(x)TypeOf(nil) is nil; ValueOf(nil) is an invalid Value
2. Reflection object to interface valuev.Interface() gives the value back as any; assert it to use itv.Interface().(float64)Panic if the field is unexported; ok == false for a wrong type
3. To modify a reflection object, it must be settableYou 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.

QuestionMethodValueOf(x)ValueOf(&x).Elem()Field of an unexported name
Is it a real variable I could take the address of?CanAddr()falsetruedepends on the parent
May I assign to it?CanSet()falsetruefalse
May I call Interface() on it?CanInterface()truetruefalse

The kinds you meet every day.

KindTypical TypeGetterSetter
BoolboolBool()SetBool
Int, Int8 ... Int64int, time.DurationInt()SetInt
Uint ... Uint64, Uintptruint8, uint64Uint()SetUint
Float32, Float64float64, CelsiusFloat()SetFloat
Stringstring, IDString()SetString
Slice, Array[]byte, [4]intLen(), Index(i)Set, SetLen, Index(i).Set*
Mapmap[string]intMapKeys(), MapIndex, MapRangeSetMapIndex
Structtime.Time, UserNumField(), Field(i)Field(i).Set*
Pointer*UserElem()Set
Interfaceerror, anyElem()Set
Funcfunc(int) stringCallSet
Chanchan intSend, Recvnone

Do I need it?

SituationReflect?Better first try
Many types, same algorithm, known at compile timenogenerics or an interface
A fixed handful of typesnoa switch v := x.(type)
One type, many call sitesnowrite the code, or go generate it
Shape known only at run time (codec, ORM, validator, config)yesone small cached package
Names come from untrusted inputnoan 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.

ChoiceStrengthWeakness
Static code (switch, interface, generics)Checked at build, fast, readableYou list every type up front
ReflectionOne function serves types it has never seenRun-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 repetitionBuild step, generated files in review
Struct tags plus reflectionMetadata lives next to the fieldTags 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 ​

  1. "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.
  2. "Kind and Type are the same." A Celsius has Kind float64 but Type Celsius; code that asserts on Type and code that switches on Kind behave differently.
  3. "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)
interface value (any)dynamic type: main.Celsiusdynamic value: 21.5reflect.TypeKind(), Name(), NumField(), Field(i), Elem()reflect.ValueKind(), Float(), Field(i), CanSet(), Set*()Law 1: reflect.TypeOf(x)Law 1: reflect.ValueOf(x)Law 2: v.Interface(), then a type assertion x.(Celsius)Law 3: to modify a reflection object, the value must be settableValueOf(x) holds a copy: CanSet() is false, Set panics "using unaddressable value"ValueOf(&x).Elem() is the variable itself: CanSet() is true

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.

go
// 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()
}
CallResult for Celsius(21.5)Note
reflect.TypeOf(x).String()laws.CelsiusPackage-qualified
reflect.TypeOf(x).Name()CelsiusEmpty for unnamed types such as []int
reflect.TypeOf(x).PkgPath()academy/reflect/lawsEmpty for built-in types
reflect.TypeOf(x).Kind()float64The underlying category
reflect.ValueOf(x).Float()21.5Getter chosen by Kind
reflect.TypeOf(nil)nilGuard 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 method

Real 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.

NeedCallAllocates?Panics when
Back to anyv.Interface()boxing a non-pointer value allocatesunexported field
Back to a concrete typev.Interface().(T)samewrong type (single-value form)
Back to a concrete type without boxingreflect.TypeAssert[T](v)nonever; returns ok
Primitive without boxingv.Int(), v.String(), v.Float()nowrong Kind
Check firstv.CanInterface()nonever

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, int

Real 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.

QuestionCompare TypeSwitch on Kind
Is it exactly time.Time?t == reflect.TypeFor[time.Time]()no, Kind is struct
Is it any integer, named or not?nocase 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
go
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.

ValueKind()Elem() givesGuard
&u where u is UserPointerthe User variableIsNil()
(*User)(nil)Pointerzero Valuecheck IsValid() after Elem()
any(7) seen as a struct field of type anyInterfacethe int 7IsNil() first
[]int{1} (a Type)Sliceint (type's Elem())none
map[string]int (a Type)Mapint; Key() is stringnone

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.1
reflect.ValueOf(x)reflect.ValueOf(&x).Elem()x = 3.4x = 3.4copy insidethe interfacepointer (&x)Elem() follows itCanAddr() false, CanSet() falseSetFloat panics: unaddressable valueCanAddr() true, CanSet() trueSetFloat(7.1) changes x itselfNever settable, even through a pointerunexported field (secret int)"using value obtained using unexported field"map element, v.MapIndex(k)use SetMapIndex; elements are not addressable

Real 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 holdCanAddr()CanSet()Why
ValueOf(x)falsefalsea copy sits in the interface
ValueOf(&x).Elem()truetruethe variable itself
ValueOf(&s).Elem().Field(i), exportedtruetruefield of an addressable struct
same, unexported fieldtruefalseset denied by export rules
ValueOf(s).Field(i)falsefalsestruct passed by value
ValueOf(slice).Index(i)truetrue (if exported element)slices are backed by an array
ValueOf(arr).Index(i)falsefalsearray copied into the interface
v.MapIndex(k)falsefalsemap 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:

MistakePanic text (Go 1.27.4)
Set on a copyreflect: reflect.Value.SetString using unaddressable value
Set an unexported fieldreflect: reflect.Value.SetInt using value obtained using unexported field
Wrong setter for the kindreflect: call of reflect.Value.SetString on int Value
Elem on a structreflect: call of reflect.Value.Elem on struct Value
Set a value of another typereflect.Set: value of type string is not assignable to type int
Use of the zero Valuereflect: 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 paths

Real 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".

go
// 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
}
MethodOnReturnsPanics when
NumField()Type, Valuefield countnot a struct (reflect: NumField of non-struct type int)
Field(i)TypeStructFieldi out of range
Field(i)ValueValuenot a struct (reflect: call of reflect.Value.Field on int Value)
FieldByName(n)Type(StructField, bool)not a struct
FieldByName(n)ValueValue, zero if absentnot a struct
FieldByIndex(path)bothnested fielda nil embedded pointer on the path (use FieldByIndexErr)
VisibleFields(t)packageall reachable fieldst 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 value

Real 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.

ConventionMeaningLibrary
json:"name,omitempty"key, optionencoding/json
json:"-"skipencoding/json, most others
db:"column"column namesqlx, pgx (RowToStructByName)
validate:"required,min=2"rulesgo-playground/validator and the mini validator below
env:"PORT" default:"8080"variable and defaultenvconfig-style loaders
xml:"id,attr"XML attributeencoding/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 fieldAllowed?
Read Type, Name, Tag, Indexyes
Int(), String(), Len(), IsZero()yes
Interface()no, panics
Set*, Setno, panics
Call on a func fieldno, 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.

GoalCallPanics when
Write an integer fieldSetInt(n)not a settable signed integer kind
Write an unsigned fieldSetUint(n)wrong kind or not settable
Write a float fieldSetFloat(f)wrong kind
Write any assignable valueSet(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)
ResetSetZero()not settable
Test emptinessIsZero()invalid Value
Fit checkOverflowInt(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{})                       delete

Real 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).

OperationSliceArrayMap
LengthLen()Len()Len()
Element readIndex(i)Index(i)MapIndex(k)
Element writeIndex(i).Set* (addressable)needs an addressable arraySetMapIndex(k, v)
Addreflect.Appendnot possibleSetMapIndex
Removereslicenot possibleSetMapIndex(k, reflect.Value{})
MakeMakeSlice(SliceOf(t), len, cap)reflect.New(ArrayOf(n, t)).Elem()MakeMap(MapOf(k, v))
Iteratefor i := range v.Len()samev.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 value

Real 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.

go
// 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
}
CaseWhat happens
Unknown or unexported nameMethodByName returns the zero Value; check IsValid()
Pointer-receiver method on a valueinvisible; pass &c
Variadic functionpass the extra arguments individually; Call builds the slice
Argument of the wrong typepanic reflect: Call using string as type int
nil argumentreflect.ValueOf(nil) is invalid; use reflect.Zero(t) for a typed nil
Callee panicsthe panic unwinds through Call; recover where you call
Call on a method value of an unexported fieldpanics

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.

go
// 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
}
NeedCallResult
A new *Treflect.New(t)pointer Value, .Elem() is settable
An unaddressable zeroreflect.Zero(t)read-only zero value
A slice type from an element typereflect.SliceOf(t)type []T
A map typereflect.MapOf(k, v)type map[K]V
A pointer typereflect.PointerTo(t)type *T
A function typereflect.FuncOf(in, out, variadic)type func(...)
A struct typereflect.StructOf(fields)anonymous struct, exported fields only
A function bodyreflect.MakeFunc(ft, impl)callable function Value
A named type or a type with methodsimpossiblewrite 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.

TestTypical usePitfall
t.Implements(iface)pick custom marshalerscheck PointerTo(t) too
t.AssignableTo(u)before Seta named type is not assignable to its underlying type
t.ConvertibleTo(u)before Convertconvertible does not mean lossless
t.Comparable()before using as a keya struct with a slice field is not comparable
v.Comparable()before == on Interface() valueschecks 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 field

Real 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.

go
// 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 ""
}
CaseDeepEqualWhat to use instead
nil versus empty slice or mapfalsecmpopts.EquateEmpty() or normalise before comparing
NaN valuesfalsecmpopts.EquateNaNs() or math.IsNaN
time.Timerepresentation-sensitivet1.Equal(t2), cmpopts.EquateApproxTime
Funcsfalse unless both nilcompare behaviour, not funcs
Unexported fieldscomparedcmpopts.IgnoreUnexported
Floating toleranceexact bitscmpopts.EquateApprox(0, 1e-9)
Ordering of a set-like sliceorder matterscmpopts.SortSlices
error valuespointer or representationerrors.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.

Aspectreflect.DeepEqualcmp.Equal / cmp.Diff
Part ofstandard libraryexternal module github.com/google/go-cmp
Unexported fieldscomparedpanic unless IgnoreUnexported or AllowUnexported
Custom equalitynoneEqual methods, Comparer, Transformer
Outputbool onlyDiff returns a path-annotated diff
nil versus emptydifferentdifferent unless EquateEmpty
Intended forquick checks, production-safe walkstests 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.

GoAdditionUse
1.17reflect.VisibleFields, StructField.IsExported, Value.CanConvertfields reachable by name, readable export check, safe conversion check
1.18reflect.Pointer and PointerTo (renaming Ptr, PtrTo), Value.CanInt/CanUint/CanFloat, SetIterKey, FieldByIndexErr, UnsafePointerclearer kinds, safe getters, nil-embedded-pointer errors
1.20Value.SetZero, Value.Grow, Value.Comparable, Value.Equalzero, grow and compare helpers
1.21ValueOf no longer forces heap escape; Value.Clearstack-friendly values; clear a map or slice
1.22reflect.TypeFor[T](); PtrTo deprecated; Value.IsZero true for negative zerotyped type lookups, consistent zero test
1.23Value.Seq, Value.Seq2, Type.CanSeq, Type.CanSeq2, Type.OverflowInt and siblings, SliceAtrange-style iteration
1.25reflect.TypeAssert[T](v)assert without allocation
1.26Type.Fields, Type.Methods, Type.Ins, Type.Outs, Value.Fields, Value.Methodsiterators 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 string
ns per operation (one run, Apple M4 Pro, Go 1.27.4; bars are on a square-root scale)direct field writereflect by index (cached Value)reflect by name (FieldByName)tag Lookup every call (3 fields)tag read from a cacheValue.Interface() on a string0.251.424781.011, 16 B, 1 allocMoral: lookups by name and parsing per call dominate; resolve once per type, then walk indexes.

Real 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.

go
// 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
}
CostWhere it comes fromRemedy
FieldByName, MethodByNamelinear or map lookup by string on every callresolve once to an index path; keep []int
Tag.Get, Tag.Lookupstring parsing on every callparse at first use; store in the plan
Interface()boxing allocates for non-pointer valuesuse Int(), String(); or reflect.TypeAssert (1.25)
reflect.New, MakeSlice, MakeMapreal allocationsreuse buffers; pool with sync.Pool
Type lookups for genericsnone (compile-time)prefer generics when types are known
Contention on a global cachea mutex around every readsync.Map or build immutable plans and publish with atomic.Pointer
Cold startfirst call per type builds the planwarm 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 both

Real 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.

TechniqueChecked whenSpeedCost to the team
Plain code, interfacescompile timefastestwrite each type
Genericscompile timefastcannot see fields or tags
go generatebuild time (and generated code compiles)fastgenerator in the toolchain, committed output
reflectrun timeslower; mitigablepanics, harder review
reflect plus unsafenothingfastest reflectivememory-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 %+v

Real 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 packageWhat it reflects overWhat is cachedIf it fails
encoding/jsonstruct fields, tags, Marshaler methodsencoder and field list per Typeerrors such as json: unsupported type: chan int
fmtany value for %v, %+v, %#vnone; walks every timeprints %!v(PANIC=...) if a method panics
text/templatefields and methods by namenoneexecution error naming the field
sqlx, pgx.RowToStructByNamedb tags, columnscolumn map per Typemissing destination name x (sqlx)
go-playground/validatorvalidate tagsparsed rules per Typepanics for an unknown tag at first use
DI container (for example uber-go/dig)constructor parameter and result typesgraph of providersan error naming the missing type
go-cmp, testifyany value for diffsnonereadable diff
net/rpcexported methods and their signaturesservice mapregistration 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 exist

Real 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).

RiskExampleDefence
Arbitrary method callMethodByName(userInput)allow-list map built at compile time
Mass assignmentbind request into the domain structbind into a DTO, copy fields explicitly
Type confusionreflect.New(typeFromInput)a closed set of constructors
Panic on bad dataCall with user argumentsvalidate counts and types, recover at the edge
Resource usedeep or cyclic structuresdepth limit, as in miniencode
Reading private dataunsafe to bypass CanInterfacedo 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 value

Real 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.

ItemStatusGuidance
reflect.SliceHeader, StringHeaderdeprecatedunsafe.Slice, unsafe.String
Value.UnsafeAddrlegacyuintptr(v.Addr().UnsafePointer()) per the documentation
reflect.NewAt, SliceAtneeds unsafe.Pointeronly for FFI and serialisation internals
internal/reflectlitestdlib onlycannot be imported by you
go vet structtagchecks tag syntaxrun it in CI
go vet and reflect misusecannot detecttests 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 usable

Real 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 map

Real 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 withCauseFix
... using unaddressable valueSet* on a copypass a pointer, take Elem()
... using value obtained using unexported fieldSet* on a private fieldcheck CanSet()
...Interface: cannot return value obtained from unexported field or methodInterface() on a private fieldcheck CanInterface()
call of reflect.Value.X on K Valuemethod X invalid for kind Kswitch on Kind() first
X of non-struct type TType struct method on another kindcheck t.Kind() == reflect.Struct
call of reflect.Value.X on zero Valueinvalid Valuecheck IsValid()
reflect.Set: value of type A is not assignable to type Bassignment mismatchAssignableTo or Convert
reflect: Call using A as type Bwrong argumentcheck AssignableTo per argument
reflect: Call with too few/many input argumentsaritycompare with Type.NumIn()
reflect.StructOf: field "x" is unexported but missing PkgPathlower-case name given to StructOfuse 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.

MethodLegal kindsPanics otherwise with
Len()Array, Chan, Map, Slice, String, pointer to Arraycall of reflect.Value.Len on K Value
Index(i)Array, Slice, Stringsame pattern
MapKeys, MapIndex, MapRangeMapsame pattern
Field, NumField, FieldByNameStructsame pattern
Elem()Interface, Pointersame pattern
IsNil()Chan, Func, Interface, Map, Pointer, Slicesame pattern
Int()Int ... Int64same pattern
CallFuncsame pattern
IsZero()any valid Valuepanics on invalid
IsValid()any, including the zero Valuenever

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.

SolutionHowAdvantageCost
Reflective validator with a plan cacheparse tags once, walk Index pathsone function validates every form typetag typos are run-time errors
Generated validatorsgo generate from tags or schematyped, fast, checked at buildbuild step
Explicit Validate() methodshand-written per typeclearest to read and testrepetitive
go
// 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.

go
// 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 featureIn miniencodeMissing on purpose
Tag name, omitempty, -yesstring, omitzero options
Sorted map keysyes (string keys only)integer keys, TextMarshaler keys
Pointers, interfacesyesMarshaler and TextMarshaler hooks
Cycle protectiondepth limit of 32the real codec detects cycles and returns json: unsupported value: encountered a cycle via *main.N
HTML escaping, float formatting rulesnomany details of strconv use
Encoder cache per typenoencoding/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).

go
// 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.

go
// 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 ​

SymptomLikely causeCheck
panic: reflect: reflect.Value.SetX using unaddressable valueValueOf(x) instead of ValueOf(&x).Elem()pass a pointer
cannot return value obtained from unexported fieldInterface() on a private fieldCanInterface() or skip !IsExported()
Field is "missing" in outputlower-case nameexport it, or add a custom marshaller
Tag option ignoredtypo or missing quotesgo vet (structtag) and Tag.Lookup
NumField of non-struct type *Tforgot Elem()Indirect first
Test shows identical values but failsnil versus empty, time zone, unexported fieldcmp.Diff
Latency grows with request rateper-request lookups and tag parsingcache a plan per Type
Race detector reports the cachemap without a locksync.Map or build once and publish

Choosing ​

SituationRecommendedExtra techniqueReason
Encode, decode, print arbitrary user typesreflect in a libraryper-type plan cachethe types are unknown by definition
Same algorithm over known typesgenericsconstraints from cmp.Ordered or your ownchecked at compile time
Known set of types, per-type behaviourtype switch or interfacego generate for boilerplatesimplest, fastest
Validation of request DTOstag-driven validatorexplicit Validate() for cross-field rulestags suit local rules only
Config from environment or filestag-driven loadererrors collected with errors.Joinone place for defaults
DB rows to structssqlx-style scan or pgx.RowToStructByNamesqlc for fully typed queriestag map cached per type
Test comparisonscmp.Diff with optionsreflect.DeepEqual for plain datareadable failures
Call methods by name from inputregistry mapsignature filter at registrationno MethodByName on untrusted names
Hot loop over a fixed typedirect codebenchmark before and afterreflection is about 5 to 100 times slower per operation here
Peek at private fieldsdo notexport an accessorunsafe voids memory-safety guarantees
Are the types knownwhen you write the code?Same algorithm, manytypes, compile-time list?Shape known onlyat run time?nonoyesyesyesPlain codeinterfaces, genericsGenerics or go generatetyped, checked at buildYes: use reflect, in one small packagecodecs (encoding/json), ORMs and scanners (sqlx, pgx), validators, config loaders, DI, go-cmpCache a plan per reflect.Type, return errors, never reflect over a type name taken from untrusted input

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 types

Distributed 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× ​

LoadConcernAction
1×Correct panics-to-errors translationtests with odd types: pointers to pointers, nil, embedded, unexported
10×Allocation and tag parsing visible in profilescache a plan per Type; prefer index paths; pprof allocation profile
100×Codec and scanner CPU dominategenerated code (sqlc, easyjson, Protobuf) for the few hottest types, keep reflection for the long tail
sql
-- 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:

go
// 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 ​

PHPGoNote
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)nonenot 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.GetPHP attributes are typed classes; Go tags are untyped strings
ReflectionMethod::invokeMethodByName(...).Call(...)Go panics on a wrong argument; PHP throws
ReflectionNamedTypereflect.TypegetName() is Name()/String()
class_exists($name), new $nameno equivalentGo cannot make a type from a string; use a registry map
Laravel container auto-wiring by type hintswire (codegen) or a manual constructorLaravel reads constructor types with ReflectionClass per resolve; Go prefers explicit wiring
php
$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).

  1. 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)
  1. 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
  }
  1. 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
  1. 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
  1. Make go vet complain: add a field A string with the tag `json:name` to any struct and run go 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 call reflect.ValueOf("x").SetString("y") and run go vet: no warning; go run panics with the text from the first step.
  2. Break the validator: add validate:"emial" to a field and call validate.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).
  3. Reproduce a production mix-up: in deepeq change Cases to compare []int(nil) with []int{} under cmpopts.EquateEmpty() and watch cmp.Equal say true while reflect.DeepEqual says false. Expected, not run here as a separate command; the Diff test covers the same rule.
  4. Point the scanner at a real database with database/sql and a driver, map SELECT id, name, email, created_by FROM users into []User with scan.All. Expected, not run: it needs a PostgreSQL server; the fake rows in scan_test.go stand in for it.

Common misconceptions ​

BeliefReality
reflect.ValueOf(x).SetInt(5) changes xValueOf(x) copies; use ValueOf(&x).Elem()
Kind and Type are the samea type ID int has Kind int and Type ID
Reflection can read and write private fieldsInterface() and Set* panic on them; unsafe is the only way and it voids safety
Tag.Get returning "" means no tagit may be present and empty; use Tag.Lookup
DeepEqual is == for big valuesnil differs from empty, NaN never equals, funcs never equal, unexported fields count
cmp.Equal is DeepEqual but fasterit is stricter and more informative; it panics on unexported fields by default
Reflection always allocatesgetters and setters on a held Value do not; boxing with Interface() does
ValueOf always forces the argument onto the heapnot since Go 1.21
Generics replace reflectionthey cannot see fields or tags; they replace it for type-uniform algorithms
go vet finds reflect misuseit checks tag syntax only; unaddressable sets are found by tests
MethodByName sees all methodsexported ones in the method set of the exact type; pointer-receiver methods need a pointer
StructOf can build a type with methodsit builds anonymous structs with exported fields only
I can look up a type by its name stringthere is no such function; build a registry
Reflection is safe on untrusted namesMethodByName(input) runs any exported method; use an allow-list
reflect.Ptr is goneit is an alias of reflect.Pointer

Cheat sheet ​

TopicRemember
Entry pointsreflect.TypeOf(x), reflect.ValueOf(x), reflect.TypeFor[T]() (Go 1.22)
Back to a valuev.Interface().(T) or reflect.TypeAssert[T](v) (Go 1.25)
Settablereflect.ValueOf(&x).Elem(); check CanSet()
Kind versus Typeswitch on Kind for families; compare Type for exact types
Nil guardsIsValid() after Elem()/FieldByName, IsNil() before Elem() on pointers
Struct walkNumField, Field(i), IsExported(), Tag.Lookup, Index paths
Unexportedreadable by kind getters, never by Interface() or Set*
CallingMethodByName(n).Call(args); check arity and AssignableTo first
MakeNew, MakeSlice, MakeMap, SliceOf, MapOf, StructOf (exported fields only)
RelationsImplements (check *T too), AssignableTo, ConvertibleTo, Comparable
DeepEqualnil slice is not empty slice; NaN and funcs are never equal; unexported fields count
go-cmpcmp.Diff(want, got, opts...); tests only; IgnoreUnexported, EquateEmpty
Costcache a plan per reflect.Type; resolve names to index paths once
Alternativesinterface, generics, go generate, in that order
Securityallow-list instead of MethodByName(input); bind into DTOs
Panic textsstart with reflect:; read method, kind and the word unaddressable or unexported
Library usersencoding/json, fmt, text/template, database/sql scanners, validators, DI containers

Self-check: questions & answers ​

Show:
  • 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 ​

TermMeaning
reflectionA program inspecting and manipulating its own types and values at run time
laws of reflectionThe three rules from the Go blog: interface to object, object to interface, settable to modify
reflect.TypeInterface describing a type: kind, name, fields, methods, element type
reflect.ValueStruct holding a value plus flags: addressable, read-only, method
reflect.TypeOfReturns the Type of the dynamic value in an interface
reflect.ValueOfReturns 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.TypeAssertGo 1.25 generic assertion from a Value without an extra allocation
KindThe 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.PointerThe Kind of pointers; reflect.Ptr is the old alias
settableA Value that can be assigned to: addressable and not from an unexported field
addressableA Value that refers to a variable, not a copy; CanAddr()
CanSetReports whether Set* is legal
CanInterfaceReports whether Interface() is legal
IsExportedTrue for upper-case field or method names (PkgPath empty)
NumField, FieldCount and access struct fields by index
FieldByNameLooks a field up by name; costs more than an index
VisibleFieldsAll fields reachable by name, including promoted ones
StructTagThe raw tag string after a field
Tag.GetValue of a tag key; empty string when absent or empty
Tag.LookupValue and an ok flag for presence
SetString, SetIntKind-specific setters
SetAssigns an assignable Value
unaddressable valueThe state that makes Set* panic: the Value is a copy
ConvertConverts a Value like a Go conversion T(x)
CallInvokes a function Value with []Value arguments
MethodByNameFinds an exported method in the method set of the held type
reflect.NewAllocates a zero value and returns a pointer Value
MakeSlice, MakeMapCreate slices and maps from a Type
SliceOf, MapOfCreate slice and map types
StructOfCreates an anonymous struct type from exported fields
MakeFuncCreates a function Value backed by your func([]Value) []Value
ImplementsWhether a type satisfies an interface type
AssignableTo, ConvertibleToType-level checks before Set and Convert
DeepEqualRecursive equality with special cases for nil, NaN, funcs and unexported fields
NaNNot-a-number; unequal to itself, so DeepEqual of values containing it is false
go-cmpgithub.com/google/go-cmp, a comparison library with options and diffs
allocationA heap allocation; boxing a value with Interface() may cause one
type cacheA map from reflect.Type to a precomputed plan
go generateTool that runs generators named in //go:generate comments; output is committed
code generationProducing Go source ahead of time so reflection is not needed at run time
encoding/jsonThe standard codec that reflects over struct fields and tags
ORMObject-relational mapper; reflects over structs to build SQL and scan rows
validatorA library that checks struct fields against tag rules
DI containerA dependency-injection container that reads constructor parameter types
untrusted type namesType or method names from input; never resolve them with reflection, use an allow-list
sqlxA library that scans database rows into structs using db tags
reflectliteinternal/reflectlite, a slim reflect for use inside the standard library
unsafePackage that bypasses type and visibility rules; voids safety guarantees
ReflectionClassPHP's class-based reflection entry point
attributesPHP 8 typed annotations read via getAttributes(); Go uses struct tags
zero ValueThe invalid Value{}; IsValid() is false and most methods panic
Seq, Seq2Go 1.23 range-style iterators over a Value

References ​

Built by Morteza Negahi