reflection: types and values
Reflection is a program reading its own types at run time. reflect.TypeOf describes the type and ValueOf holds a value, and together they let a package such as encoding/json walk a struct it has never seen. It is slower than a direct field access and it gives up the compiler's checks, which is why the standard library uses it and application code usually should not.
TypeOf, ValueOf and Kind
A Type is the declared type, with its name and package, and the Kind is the underlying shape: struct, int, slice, pointer. The two differ for a named type, which is why a program that switches on Kind handles time.Duration and int64 the same way. The fields of a struct come with their names, types and tags.
package main
import (
"fmt"
"reflect"
)
type User struct {
Name string `json:"name"`
Age int `json:"age"`
}
func main() {
u := User{Name: "ada", Age: 36}
t := reflect.TypeOf(u)
fmt.Println("type:", t, "kind:", t.Kind())
v := reflect.ValueOf(u)
fmt.Println("value:", v, "kind:", v.Kind())
for i := 0; i < t.NumField(); i++ {
f := t.Field(i)
fmt.Println(f.Name, f.Type, f.Tag)
}
}
go build -o app main.go && ./app
type: main.User kind: struct
value: {ada 36} kind: struct
Name string json:"name"
Age int json:"age"
The type prints with its package, the value with its fields in braces, and the tag is a string that the next lesson reads. NumMethod and Method describe the method set the same way, and a Value has its own Kind that can be Invalid for a zero Value.
Fields by name
A field is writable only through a value that came from a pointer, which is why the program takes ValueOf(&u).Elem(). CanSet reports it before the panic, and FieldByName returns an invalid value for a field that does not exist, which IsValid detects. The typed setters keep the conversion rules the compiler would have applied.
package main
import (
"fmt"
"reflect"
)
type User struct {
Name string
Age int
}
func main() {
u := User{Name: "ada", Age: 36}
v := reflect.ValueOf(&u).Elem()
field := v.FieldByName("Name")
fmt.Println("valid:", field.IsValid())
fmt.Println("can set:", field.CanSet())
field.SetString("grace")
age := v.FieldByName("Age")
age.SetInt(37)
fmt.Printf("%+v\n", u)
}
go build -o app main.go && ./app
valid: true
can set: true
{Name:grace Age:37}
Without the pointer the same field answers CanSet false, and SetString panics. An unexported field is not settable even through a pointer, because the package boundary still applies. A decoder uses exactly this pair: CanSet for a field it may fill and IsValid for one it should skip.
Methods by name
MethodByName returns a function value that takes its arguments as a slice of reflect.Value and returns one. The method set of the pointer includes the pointer methods, which is why the value below is a *Counter. A call through reflection is slower than a direct call by an order of magnitude, and a signature mistake is a panic at run time instead of a compile error.
package main
import (
"fmt"
"reflect"
)
type Counter struct {
n int
}
func (c *Counter) Add(delta int) int {
c.n += delta
return c.n
}
func (c *Counter) Value() int {
return c.n
}
func main() {
c := &Counter{n: 10}
v := reflect.ValueOf(c)
add := v.MethodByName("Add")
result := add.Call([]reflect.Value{reflect.ValueOf(5)})
fmt.Println("Add(5) returned:", result[0].Int())
value := v.MethodByName("Value")
fmt.Println("Value() returned:", value.Call(nil)[0].Int())
}
go build -o app main.go && ./app
Add(5) returned: 15
Value() returned: 15
The two calls went through the method table and the counter did change, which is the mechanism an RPC framework or a test fake uses to call a handler by name. A program that knows the method at compile time calls it directly; reflection is for the layer that receives the name as a string or from a tag.
The wrong kind
A typed getter checks the kind and panics when it does not match. The program asks a string value for an int and the runtime prints the call and the type, which is the failure a decoder turns into an error with recover or, better, avoids by checking Kind first.
package main
import (
"fmt"
"reflect"
)
func main() {
v := reflect.ValueOf("text")
fmt.Println("kind:", v.Kind())
fmt.Println("int:", v.Int())
}
go build -trimpath -o app main.go && ./app
kind: string
panic: reflect: call of reflect.Value.Int on string Value
goroutine 1 [running]:
reflect.Value.Int(...)
reflect/value.go:1471
main.main()
./main.go:11 +0x1af
exit status: 2
The message names the method and the kind, and the stack names the line. Kind was printed before the panic because the program asked for it first; a program that checks it and branches never reaches the panic. The next lesson reads the tags that sit on the fields above.
Reflection at the edges
Reflection belongs at the edge of a program: a decoder, an encoder, a dependency injection container, a test helper that compares two values. Inside the core it costs speed, hides the data flow from a reader and turns compile errors into run-time panics. The rule of thumb: if a generic function or an interface can do the job, it is better than reflection; if the type arrives as a string, reflection is the only tool.
Three checks keep a reflective function honest. IsValid before anything else, Kind before a typed getter, and CanSet before a setter. The standard library follows them in encoding/json, and the next two lessons read that code's behaviour through the tags and the errors it produces.
Exercises
- Print reflect.TypeOf(time.Second).Kind() and its name. Why does a decoder for JSON numbers care about the difference?
- Take the address away from the field example and read the panic. Which check would have prevented it, and what would a decoder do instead?
- Call a method with the wrong number of arguments and read the panic. Where is the error caught in a program that must not crash?
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What is the difference between Type and Kind?
Answer
Type is the declared type with its package; Kind is the underlying shape
A named int64 and a Duration share a Kind.
-
What does ValueOf return for a struct field?
Answer
A Value that is readable but not settable without a pointer
CanSet is true only through an addressable value.
-
How is a field made settable?
Answer
Through ValueOf(&v).Elem()
The pointer gives addressability.
-
What does FieldByName return for a missing field?
Answer
An invalid Value, which IsValid reports
A decoder skips it.
-
What does MethodByName return?
Answer
A function value called with a slice of Values
The call is checked at run time.
-
Why does the method example take a pointer?
Answer
The method set of the pointer includes the pointer methods
A value would miss Add and Value.
-
What does the wrong-kind failure look like?
Answer
A panic that names the method and the Kind
Kind is the guard before the getter.
-
Where does reflection belong?
Answer
At the edges: decoders, encoders, test helpers
It costs speed and type safety.
-
What is better than reflection when it fits?
Answer
A generic function or an interface
The compiler keeps its checks.
-
Which check comes before a typed getter?
Answer
Kind
The getter panics on a different Kind.
The code on this page was run with go 1.26.10 on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev