Skip to content
Tutorials Center
My learning

Topics

Go Reference ยท Logging, Flags and Testing

Go reflect package

Reference for the Go reflect package: TypeOf, ValueOf, Kind, struct fields and tags, Elem, Set and CanSet, calling methods, DeepEqual and when to avoid reflection.

Reflection lets a program inspect and change values whose types it does not know at compile time. The package reflect offers two entry points: reflect.TypeOf(x) returns a reflect.Type that describes a type (name, kind, fields, methods), and reflect.ValueOf(x) returns a reflect.Value that holds the data and can read it, and sometimes write it.

Packages such as encoding/json, fmt, text/template and database/sql use reflection to handle any struct you give them. In application code, plain types, generics and interfaces are almost always clearer and faster; reach for reflect when you build a generic library, a validator, an encoder or a test helper.

Go
t := reflect.TypeOf(3.5)
fmt.Println(t.Name(), t.Kind()) // float64 float64

Try it

Go Walking a struct and its tags

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Go Setting values, Elem and DeepEqual

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Syntax

Go
func TypeOf(i any) Type
func ValueOf(i any) Value
func TypeFor[T any]() Type          // Go 1.22
func DeepEqual(x, y any) bool
func Indirect(v Value) Value
func New(typ Type) Value
func Zero(typ Type) Value
func MakeSlice(typ Type, len, cap int) Value
func Append(s Value, x ...Value) Value

type Type interface { Name() string; Kind() Kind; Elem() Type; NumField() int; Field(i int) StructField; NumMethod() int; /* ... */ }

func (v Value) Kind() Kind
func (v Value) Interface() any
func (v Value) Elem() Value
func (v Value) Field(i int) Value
func (v Value) FieldByName(name string) Value
func (v Value) MethodByName(name string) Value
func (v Value) Call(in []Value) []Value
func (v Value) Set(x Value)
func (v Value) CanSet() bool
func (v Value) IsNil() bool
func (v Value) IsValid() bool
func (v Value) IsZero() bool
Name Description
Kind The underlying category: Int, String, Struct, Slice, Map, Pointer, Interface, Func, ... For type ID int, Type.Name() is ID but Kind() is Int.
Elem For a pointer type or value, what it points to. For slices, arrays, maps and channels (on a Type), the element type.
StructField Name, Type, Tag, Index, Anonymous, and IsExported().
StructTag Get(key) returns the value or ""; Lookup(key) also says whether the key exists.

Panics: methods fail with a *reflect.ValueError panic when used on the wrong kind (NumField on an int, Elem on a struct, Set on an unaddressable value, reading an unexported field with Interface()).

Usage notes

  • Settable means addressable. Pass a pointer, call .Elem(), and the resulting Value can be set. ValueOf(x) of a plain value holds a copy and CanSet() is false.
  • Unexported fields can be read with String(), Int() and similar (not Interface()), but never set.
  • Interfaces. TypeOf of a nil interface returns nil. To get an interface type use TypeFor[error]() or TypeOf((*error)(nil)).Elem().
  • Check validity. FieldByName on a missing field returns the zero Value; test IsValid() before using it.
  • DeepEqual rules. A nil slice is not equal to an empty one; maps compare by contents; functions are equal only if both are nil; cyclic data is handled. Prefer slices.Equal / maps.Equal for simple cases (they are faster and type-safe).
  • Cost. Reflection is many times slower than direct code and defeats compile-time checks. Cache Type information instead of recomputing it for every call.
  • Struct tags (`json:"name"`) are the main way libraries read configuration from your types; read them with Tag.Lookup.
  • reflect.Value.Seq and Seq2 (Go 1.23) iterate over values as range-over-func sequences.
  • Prefer generics when the types are known at compile time but vary between calls.