Skip to content
Tutorials Center
My learning

Topics

Lesson 122 of 147 ยท Advanced Go

Reflection

Learn Go reflection - reflect.TypeOf and ValueOf, Kind, reading struct fields and tags, setting values, calling methods, a mini validator and encoder, and what it costs.

Go is statically typed: the compiler knows the type of every variable, and fmt.Println(x) is checked long before the program runs. But some programs cannot know types in advance. encoding/json must encode any struct you hand it. fmt prints values of types it has never heard of. ORMs, validators and dependency-injection containers all need to look at a value and ask "what are you, and what is inside you?"

The reflect package answers that. Reflection is the ability of a running program to inspect and manipulate its own values and types. It is powerful and it is also slow, unchecked by the compiler and easy to misuse, so the Go proverb is: "Clear is better than clever. Reflection is never clear." This lesson shows how it works so you can read library code, write the occasional reflective helper, and recognize when you should not.

Types and values: the two entry points

Everything in reflect starts from a value stored in an any. Two functions open the door:

  • reflect.TypeOf(x) returns a reflect.Type: what the value is (its name, kind, fields, methods).
  • reflect.ValueOf(x) returns a reflect.Value: the data itself, which you can read and sometimes change.

Both rely on the interface layout from interface internals: an any holds a type descriptor and the data, and reflection simply hands you access to both halves.

A type has a name and a kind. The kind is the underlying category (reflect.Int, reflect.String, reflect.Struct, reflect.Slice and about two dozen more). Two different types can share a kind:

Go Type, Kind and Value

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.

Celsius has the name Celsius but the kind float64, which is why a switch on Kind is how reflective code branches on "what shape is this?". Notice the pointer: *main.Point has kind ptr. To get from a pointer to the thing it points to, call Elem() on the type or the value. Similarly, Elem() on a slice, array, map or channel type gives the element type.

Kinds are spelled reflect.Pointer in code (since Go 1.18; the old name reflect.Ptr still works), and they print as ptr. A kind is a small integer constant, so compare with == or use a switch.

Walking a struct: fields and tags

For a struct value, NumField() and Field(i) expose each field. On the type side, Field(i) returns a reflect.StructField with the name, type and the tag string you saw in struct tags. On the value side, Field(i) returns the field's value:

Go Listing the fields and tags of a struct

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.

Tag.Get("json") parses the conventional key:"value" format for you. Tag.Lookup also tells you whether the key existed at all. Two things to remember: Interface() (turn a reflect.Value back into an any) panics on unexported fields, so check IsExported() first; and reflection can read the value of an unexported field through methods like Int(), but it can never set it or call Interface() on it, which preserves package encapsulation.

Methods work the same way: t.NumMethod() and t.Method(i) list the exported methods in the type's method set. Interface types list their methods as well.

Changing values: addressability

reflect.ValueOf(x) receives a copy of x. Changing the copy would be pointless, so reflect refuses. To modify the original, pass a pointer and use Elem() to get the value it points to. That value is addressable (it refers to a real variable), and CanSet() reports whether you may assign to it:

Go Setting values through a pointer

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.

The output is three booleans (false, true, false) followed by {Host:example.org Port:8443 Debug:true secret:s3cr3t}. The setters are typed: SetInt, SetString, SetBool, SetFloat, SetUint and the generic Set(reflect.Value), which requires assignable types.

Calling a setter on the wrong kind or on a non-settable value panics. The program below catches the panic with recover so you can read the messages:

Go Reflection panics instead of failing to compile (recovered)

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.

Each failing line shows a message starting with reflect: or reflect.Value., such as reflect: reflect.Value.SetInt using unaddressable value. This is the price of reflection: mistakes the compiler would catch in normal code become run-time panics. Always guard with CanSet, Kind and IsValid checks when the input is not under your control.

Calling methods and functions

A reflect.Value can call functions: Call takes a slice of argument values and returns a slice of results. This is how frameworks route "call the method named X" without knowing the type:

Go Calling methods by name

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.

The pointer type has two methods (Hello and Rename) while the plain Greeter has only Hello, because pointer-receiver methods belong only to the pointer's method set. MethodByName returns an invalid Value for a name that does not exist, and calling an invalid value panics, so check IsValid() first. Call also panics if the argument count or types do not match, which is why most real code prefers an interface with a normal method call whenever possible.

Building a mini validator

Struct tags plus reflection are the classic combination. Libraries such as go-playground/validator read tags like validate:"required,min=3". Here is a tiny version that handles required and min=N for strings and integers, using only what you have learned:

Go A tag-driven struct validator

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.

The first call returns an empty list ([]). The second reports two problems, the third three (Username is required, Username needs at least 3 characters, Age must be at least 18), and the last rejects a non-struct. Two details deserve attention. IsZero() reports whether a value is its type's zero value, which is a neat generic "is it empty?" test. And one rule parser (strings.Cut on =) serves every field, so adding a rule is one more case.

Building a mini encoder

Reflection also lets you write code that walks any value recursively. This encoder turns booleans, numbers, strings, slices, maps and structs into a JSON-like text. It uses Kind to decide how to descend, and sorts map keys so the output is deterministic:

Go A recursive JSON-like encoder

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.

The real encoding/json (JSON) is this idea grown up: it handles many more kinds, caches the per-type field information so the type is analyzed only once, and implements json.Marshaler for custom behavior. Notice how the structure mirrors the data: each case handles one shape and recurses into nested values.

Building values at run time

Reflection can also create values whose types you only know while the program runs. The reflect package has a "Make" family for this, and each function returns a reflect.Value you can fill and then turn back into an ordinary value with Interface().

Go MakeSlice, MakeMap and reflect.New

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.

MakeSlice takes the slice type, a length and a capacity; reflect.Append returns the grown slice, just like the built-in append. reflect.New(t) is the run-time new(T), and its Elem() is addressable, so you can set it. SliceOf, MapOf, ArrayOf and PointerTo combine existing types into new ones. Channels have their own helpers: MakeChan, Send and Recv.

MakeFunc: a function from a template

reflect.MakeFunc builds a function of a given type whose body is a Go closure working on []reflect.Value. That lets you write one generic wrapper (logging, timing, retry) for functions of any signature:

Go Wrapping any function with MakeFunc

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.

The wrapper has exactly the type of the original, so a type assertion on the result gives you a normal callable function. Because arguments pass through []reflect.Value, every call allocates, so this suits tooling and test helpers rather than hot loops.

StructOf: a struct type made on the fly

reflect.StructOf builds a brand-new struct type from a list of reflect.StructFields, tags included. It is rare, but it is how a few libraries create row or schema types from a description:

Go Creating a struct type with StructOf

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.

Field names must be exported (start with an upper-case letter), or StructOf panics. Static code cannot name the new type, so you work with it only through reflect or by passing v.Interface() to code that itself uses reflection, such as encoding/json.

Costs and when to avoid reflection

Reflection is slower than normal code because it works through interfaces, cannot be inlined and allocates for many operations. It also gives up compile-time safety: wrong kinds, unexported fields and missing methods all become panics. And it makes code harder to read and to search.

Libraries cope by doing the reflection once per type and caching the result (field offsets, converters), then reusing it on every call. Compare that with the alternatives:

Need Prefer
Different behavior per type An interface with a method
One algorithm for many types Generics
Code for a known list of types A type switch
Repetitive boilerplate Code generation (go generate)
Truly unknown shapes (JSON, ORMs, validators) Reflection, cached

Reach for reflect last. When you do, keep the reflective code small, hidden behind a typed function, and covered by tests, because the compiler will not help you.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Given type Celsius float64, what are reflect.TypeOf(Celsius(1)).Name() and .Kind()?

    The name is the defined type's own name (Celsius). The kind is its underlying category, float64.
  2. 2. What does reflect.ValueOf(n).SetInt(5) do when n is an ordinary int variable?

    ValueOf receives a copy. To change n you must pass &n and call Elem() on the result.
  3. 3. Which fields of a struct can reflection set (assuming an addressable struct value)?

    Unexported fields can be read but CanSet reports false for them, which protects package encapsulation.
  4. 4. A type T has one value-receiver method A and one pointer-receiver method B. What do reflect.TypeOf(T{}).NumMethod() and reflect.TypeOf(&T{}).NumMethod() return?

    The method set of T contains only value-receiver methods; the method set of *T contains both.
  5. 5. Which is usually the better tool when you only need different behavior for a handful of known types?

    Type switches and interfaces are checked by the compiler, faster and easier to read. Reflection is for shapes that are genuinely unknown until run time.

Summary

  • reflect.TypeOf describes what a value is; reflect.ValueOf gives access to its data. A type has a name and a kind (its underlying category).
  • Walk structs with NumField/Field; read tags with Tag.Get or Tag.Lookup; check IsExported before Interface().
  • To modify a value, pass a pointer and use Elem(); CanSet tells you if assignment is allowed. Unexported fields are never settable.
  • MethodByName(...).Call(...) invokes methods dynamically; pointer-receiver methods exist only on the pointer type.
  • Reflection moves errors from compile time to run time (panics), so validate kinds and use IsValid, CanSet and IsZero.
  • It is slow and unclear; prefer interfaces, generics and type switches, and cache reflective work when you must use it.

Next: unsafe, cgo and Assembly steps below the type system to work with raw memory and C code.