Level: AdvancedGo Lang

Go Reflection Explained with Simple Examples

9 min read
Go Reflection featured image: TypeOf, ValueOf and struct tags

Go reflection lets a program look at its own types and values while it runs. In this post, you will learn what the reflect package does. You will also see how to read struct fields and tags and how to change values safely. Then we will build a tiny validator, which is how many real libraries work inside.

This lesson builds on Go structs explained and Go interfaces with examples. We also use the ideas from Go type assertion and type switch and Go input validation. So it helps to know those first, because reflection builds on them.

What Is Go Reflection?

In short, reflection means a program can inspect and change its own structure at run time. Normally, the compiler knows every type before the program starts. With reflection, however, your code can receive a value of any type. Then it can ask, “What are you, and what is inside you?”

Think of an X-ray machine at a hospital. A doctor does not open the patient to see the bones. Instead, the machine shows what is inside. Similarly, reflection shows the fields, tags and methods of a value without knowing its type in advance.

The reflect package has two main types. First, reflect.Type describes a type, such as its name and its fields. Second, reflect.Value holds the actual data and lets you read or change it. Together, they power encoding/json, fmt and many other packages. For example, json.Marshal uses them to find the field names of your struct.

Why Go Reflection Matters

Most of the time you do not need reflection. However, it is the secret behind many tools you use every day. So here is why Go reflection is worth learning.

  • It explains the libraries: JSON, ORMs and validators all use it.
  • Generic helpers: you can write one function that works on any struct.
  • Struct tags: you can read tags such as json:"name" and act on them.
  • Debugging tools: you can print or compare values of unknown types.
  • Better judgement: you learn when reflection is the right tool, and when it is not.

Because of this, even beginners benefit from a short tour of the package. In fact, once you see how a validator reads tags, many library errors start to make sense. Therefore, this lesson is a good investment even if you rarely write reflective code.

How Go Reflection Works

Every Go value stored in an interface carries two hidden facts, which are its type and its data. The reflect package lets you read both, which is the core of Go reflection. In Go reflection, you first call reflect.TypeOf(x), which returns the type. Next, reflect.ValueOf(x) returns the value. Then you can walk through fields, check the kind and read or set data.

Go Reflection diagram showing TypeOf and ValueOf feeding a tag validator
A value goes into reflect.TypeOf and reflect.ValueOf. TypeOf describes names, kinds and tags, and ValueOf gives access to the data for reading and setting.

Notice that reflection has a special word called kind. The kind is the basic category, such as int, string, slice, map or struct. For example, type Celsius float64 has the type Celsius but the kind float64.

The Most Used Functions

You only need a handful of functions at first, so the table below lists them.

FunctionWhat it doesExample
reflect.TypeOf(x)Returns the type of xUser
reflect.ValueOf(x)Returns the value of xThe data inside
t.Kind()Returns the categorystruct, int
t.NumField() and t.Field(i)Lists struct fieldsName, Email
f.Tag.Get("json")Reads a struct tag"name"
v.Elem().Field(i).SetString(...)Changes a fieldNew name

The Three Laws in Plain Words

The Go team describes reflection with three laws. First, reflection goes from an interface value to a reflection object. Second, it goes back from a reflection object to an interface value, using Interface(). Third, a reflection value must be settable before you can change it. In practice, that means you must pass a pointer.

Go Reflection vs Type Switches and Generics

Reflection is only one way to handle many types. For that reason, the table below compares three options.

FeatureReflectionType switchGenerics
When types are checkedRun timeRun timeCompile time
Works for unknown typesYesOnly listed typesOnly matching constraints
SpeedSlowestFastFast
Type safetyLow, errors are panicsMediumHigh
Best forTags and unknown structsA few known typesReusable typed code
Go Reflection diagram comparing reflection, type switches and generics
Reflection reads types at run time and works with any struct, while generics are checked by the compiler and a type switch handles a short list of known types.

So when should you use which? Prefer generics or a type switch whenever you can. On the other hand, use reflection when you must read struct tags or handle types you cannot list in advance.

Go Reflection Hands-On: Inspect and Validate a Struct

Now let’s try the package for real. We use a User struct with tags. Also, every output below comes from a real run on Go 1.24.

Step 1: Inspect Any Struct

First, here is the struct and a function that prints the type, the kind and every field. Because it accepts any, you can pass any struct.

type User struct {
	Name  string `json:"name" validate:"required"`
	Email string `json:"email" validate:"required"`
	Age   int    `json:"age" validate:"min=18"`
	token string // unexported
}

func inspect(v any) {
	t := reflect.TypeOf(v)
	val := reflect.ValueOf(v)
	fmt.Println("type:", t.Name(), "kind:", t.Kind())
	for i := 0; i < t.NumField(); i++ {
		f := t.Field(i)
		fmt.Printf("  %-6s %-7s json=%q exported=%v\n", f.Name, f.Type, f.Tag.Get("json"), f.IsExported())
		if f.IsExported() {
			fmt.Printf("         value=%v\n", val.Field(i).Interface())
		}
	}
}

When we call inspect(User{Name: "Asha", Email: "", Age: 15}), we get this output.

type: User kind: struct
  Name   string  json="name" exported=true
         value=Asha
  Email  string  json="email" exported=true
         value=
  Age    int     json="age" exported=true
         value=15
  token  string  json="" exported=false

Notice that the loop skips the value of token. Reading the value of an unexported field with Interface() would panic. Therefore, the code checks IsExported() first.

Step 2: Build a Tiny Validator from Tags

Next, we read the validate tag of each field and apply simple rules. This is a small version of what real validation libraries do. As a result, you can see the idea behind them in about twenty lines.

func validate(v any) []string {
	var problems []string
	val := reflect.ValueOf(v)
	t := val.Type()
	for i := 0; i < t.NumField(); i++ {
		rule := t.Field(i).Tag.Get("validate")
		fv := val.Field(i)
		switch {
		case rule == "required" && fv.IsZero():
			problems = append(problems, t.Field(i).Name+" is required")
		case strings.HasPrefix(rule, "min="):
			min, _ := strconv.Atoi(strings.TrimPrefix(rule, "min="))
			if fv.Int() < int64(min) {
				problems = append(problems, fmt.Sprintf("%s must be at least %d", t.Field(i).Name, min))
			}
		}
	}
	return problems
}

Running validate(u) on our user prints the two problems.

problems: [Email is required Age must be at least 18]

The IsZero method checks for the zero value, such as an empty string. Also, fv.Int() reads any integer kind as an int64. As a result, the same validator works on structs with many field types. Compare this with the hand-written Validate() method from the input validation lesson. Reflection saves typing, but plain code is easier to debug.

Step 3: Change a Value with a Pointer

Now let’s set a field. First, we must pass a pointer. Then we call Elem() to reach the struct itself.

pv := reflect.ValueOf(&u).Elem()
pv.FieldByName("Name").SetString("Asha Mehta")
fmt.Println("after set:", u.Name)
fmt.Println("can set token?", pv.FieldByName("token").CanSet())

The output shows that exported fields can change. In contrast, unexported fields cannot.

after set: Asha Mehta
can set token? false

Step 4: Call a Method by Name

Finally, reflection can also call methods. In fact, this is how some frameworks find handlers by name.

func (u User) Greet(greeting string) string { return greeting + ", " + u.Name }

m := reflect.ValueOf(u).MethodByName("Greet")
out := m.Call([]reflect.Value{reflect.ValueOf("Hello")})
fmt.Println("method result:", out[0])

The result is Hello, Asha Mehta. Also, only exported methods can be found this way.

Step 5: Check the Kind of Any Value

A loop with Kind() can describe unknown values.

for _, x := range []any{42, "go", 3.14, []int{1, 2}, map[string]int{"a": 1}} {
	fmt.Printf("%v -> %s\n", x, reflect.TypeOf(x).Kind())
}

The output lists the kind for each value.

42 -> int
go -> string
3.14 -> float64
[1 2] -> slice
map[a:1] -> map

Step 6: Measure the Cost

Reflection is slower than normal code. To measure it, this benchmark reads a field directly and through reflection.

BenchmarkDirect-2    	1000000000	         0.5855 ns/op	       0 B/op	       0 allocs/op
BenchmarkReflect-2   	23005450	        54.78 ns/op	       0 B/op	       0 allocs/op

On our machine, the reflection call took about 55 nanoseconds, while the direct read took less than one. That is roughly 90 times slower, but still tiny for a single call. However, it matters inside hot loops. So cache what you can, and avoid reflection in code that runs millions of times.

Common Mistakes with Go Reflection

  • Using reflection when a type switch is enough: the code becomes harder to read. So try simple tools first, and add Go reflection only when you must.
  • Setting a value without a pointer: reflect.ValueOf(u) is a copy and cannot be set. Instead, pass &u and call Elem().
  • Touching unexported fields: Interface() and Set... panic on them. Therefore, check IsExported() and CanSet() first.
  • Ignoring panics: reflection reports many mistakes as panics. So test your reflective code well.
  • Using it in hot paths: reflection costs real time. Instead, cache the type information once and reuse it.

Best Practices for Go Reflection

  • Prefer generics and interfaces, because the compiler then checks your code.
  • Keep reflection in small helper functions, so the rest of the code stays simple.
  • Check the kind before reading, since calling Int() on a string panics.
  • Cache field lookups, which saves time when you process many values.
  • Write table-driven tests, because reflective code has many edge cases.
  • Document the tags you support, so other developers know the rules. Clear notes make Go reflection code much easier to maintain.

Practice Task

To practise Go reflection, extend the validator with a max= rule for integers and a maxlen= rule for strings. Then add a field Bio string with validate:"maxlen=100". Finally, test it with a long text.

Hint: use fv.Kind() == reflect.String before calling fv.Len(). After that, write a table test with one valid user and three invalid ones.

Official Resources

These pages describe the package and the three laws in detail.

Quick Recap

  • Go reflection lets code inspect types and values at run time.
  • reflect.TypeOf describes the type, and reflect.ValueOf holds the data.
  • The kind tells you the basic category, such as struct or slice.
  • Pass a pointer and call Elem() when you need to change a value.
  • Struct tags let libraries add rules and names to fields.
  • Reflection is slower and less safe, so use it only when needed.

What’s Next?

By now, you know how many Go libraries work inside. However, real products also need bigger designs. So next, we will look at splitting one app into small services.

Coming soon: Go Microservices Basics