Reflection
What you will learn
By the end of this lesson, you will be able to:
- inspect dynamic type and value information;
- distinguish a concrete type from its
Kind; - understand validity, addressability, and settability;
- read struct tags deliberately;
- contain reflective code behind a typed API and decide when not to use it.
Mental model: runtime type inspection
Ordinary Go code uses compile-time types. Reflection lets code inspect and sometimes manipulate type information at runtime.
It powers features such as encoders, dependency tools, test utilities, and generic data mappers. It also moves many mistakes from compile time to runtime.
Type and Value
input := 42
value := reflect.ValueOf(input)
typ := reflect.TypeOf(input)
fmt.Println(typ.Name()) // int
fmt.Println(typ.Kind()) // int
fmt.Println(value.Int()) // 42
reflect.Typedescribes a Go type.reflect.Valuerepresents a runtime value.Kindis the broad representation category such as struct, slice, pointer, or string.
Defined types can have the same kind but different identities:
type UserID int64
typ := reflect.TypeOf(UserID(42))
fmt.Println(typ.Name()) // UserID
fmt.Println(typ.Kind()) // int64
Invalid and nil values
reflect.ValueOf(nil) returns an invalid Value. Check IsValid before most other operations.
For values whose kind can be nil—such as pointers, maps, slices, channels, functions, and interfaces—IsNil reports whether the represented value is nil. Calling IsNil on an unsupported kind panics.
Reflection APIs often panic when used with the wrong kind. Check preconditions and turn panics into ordinary validation errors at your boundary rather than letting arbitrary caller input reach unsafe operations.
Read a struct
type Lesson struct {
Title string `json:"title"`
Published bool `json:"published"`
}
lesson := Lesson{Title: "Reflection", Published: true}
value := reflect.ValueOf(lesson)
typ := value.Type()
for index := 0; index < value.NumField(); index++ {
fieldType := typ.Field(index)
fieldValue := value.Field(index)
fmt.Println(fieldType.Name, fieldValue.Interface())
}
Interface panics for values that cannot be interfaced, including certain unexported fields. A reusable library must inspect CanInterface and define how it handles unexported data.
Struct tags are metadata strings
field, _ := reflect.TypeOf(Lesson{}).FieldByName("Title")
name, options := field.Tag.Lookup("json")
fmt.Println(name, options)
A tag has no behaviour by itself. A package such as encoding/json reads the tag and defines its meaning. Different packages can use different keys and rules.
Change a value
This does not work because ValueOf received a copy:
lesson := Lesson{Title: "Old"}
value := reflect.ValueOf(lesson)
fmt.Println(value.CanSet()) // false
Pass a pointer and select the pointed-to value:
value := reflect.ValueOf(&lesson).Elem()
title := value.FieldByName("Title")
if title.IsValid() && title.CanSet() && title.Kind() == reflect.String {
title.SetString("New")
}
A settable value must be addressable and permitted to change. Export rules still apply.
Contain reflection behind typed boundaries
Bad public API:
func CopyAnything(dst, src any) error
The caller learns about mistakes only at runtime.
A better design may use generics, a small interface, code generation, or a typed wrapper around a reflective core. Validate inputs once and return clear errors naming the unsupported type or field.
Performance and caching
Reflection adds runtime work and can allocate, but performance conclusions require measurement. If a profile identifies repeated type inspection as important, immutable metadata can be cached by reflect.Type with concurrency-safe ownership.
Do not cache reflect.Value objects that refer to short-lived mutable values without a precise lifetime design.
Common mistakes
- Switching on
Kindand forgetting defined types: kind describes representation, not full type identity. - Calling methods before validity/kind checks: malformed input causes panics.
- Assuming tags enforce validation: only code interpreting the tag does anything.
- Reflecting over unexported fields casually: visibility rules and panic conditions still apply.
- Choosing reflection before interfaces or generics: callers lose compile-time guidance unnecessarily.
Practice
Write DescribeStruct(input any) ([]Field, error) that accepts a struct or pointer to struct and returns exported field names, types, kinds, and JSON tag names. Reject nil pointers and non-struct values without panicking.
type Field struct {
Name string
Type string
Kind reflect.Kind
JSONName string
}
func DescribeStruct(input any) ([]Field, error) {
value := reflect.ValueOf(input)
if !value.IsValid() {
return nil, errors.New("input is nil")
}
if value.Kind() == reflect.Pointer {
if value.IsNil() {
return nil, errors.New("input is a nil pointer")
}
value = value.Elem()
}
if value.Kind() != reflect.Struct {
return nil, fmt.Errorf("input has kind %s; want struct", value.Kind())
}
typ := value.Type()
fields := make([]Field, 0, typ.NumField())
for index := 0; index < typ.NumField(); index++ {
field := typ.Field(index)
if !field.IsExported() {
continue
}
jsonName := strings.Split(field.Tag.Get("json"), ",")[0]
if jsonName == "-" {
continue
}
if jsonName == "" {
jsonName = field.Name
}
fields = append(fields, Field{
Name: field.Name, Type: field.Type.String(), Kind: field.Type.Kind(), JSONName: jsonName,
})
}
return fields, nil
}
This solution checks every precondition before operations that would panic. A production tag parser may need more complete handling of embedded fields and package-specific tag rules; those behaviours should be documented and tested rather than guessed.
Summary
- Reflection inspects runtime types and values at the cost of compile-time guarantees.
- Type identity and
Kindanswer different questions. - Check validity, nil, kind, interface access, and settability before operating.
- Struct tags are inert metadata interpreted by packages.
- Prefer typed APIs and contain any reflective core behind validation and tests.
Official reference: reflect package documentation.
Ready to wrap up?
Mark this complete when you can explain the main idea and finish the practice task.