liveBook · Manning

Reflect.Indirect

As explained in Go in Practice, Second Edition

reflect.Indirect is a Go reflect function that returns the value referenced by a pointer or returns its argument unchanged when it is not a pointer.

reflect.Indirect unwraps a pointer into the reflect.Value it references and returns non-pointer values unchanged. This lets reflection code normalize unknown inputs before inspecting their types, kinds, or fields. section 13.1.3

Normalize a value before walking it

A recursive struct walker can begin with `val := reflect.Indirect(reflect.ValueOf(u))`. It then obtains `val.Type()` and examines `val.Kind()`. For a `*Person`, the normalized value is `Person`; for a `MyInt`, it remains `MyInt`. The same step therefore supports both pointer-backed and direct values. section 13.1.3

How Go in Practice, Second Edition covers it

How deep it goes
Explains pointer unwrapping and non-pointer passthrough within a recursive struct walker, stopping short of broader reflection edge cases.
Examples
Uses MyInt, simple structs, and nested Person, Name, and Address pointers in a recursive walker.
What it assumes
Assumes familiarity with Go values and pointers while introducing reflect.Value, type, kind, and recursive field inspection.
What you can do after
Build reflection walkers that handle pointer and non-pointer inputs through one normalization step.
How it connects
Connects reflect.Indirect with reflect.ValueOf, reflect.Type, reflect.Kind, pointers, and structs.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Go in Practice, Second Edition. The section links point to the parts of the book it draws on.