Inspect struct fields, tags and methods
Inspect struct fields, tags and methods
Reflection can discover the shape of a struct without knowing every field at compile time. A struct tag is metadata; a library decides what it means. Inspect exported fields and their tags to build a simple field inventory, not to expose private application state.
package main
import ( "fmt" "reflect")
type Product struct { Name string `json:"name"` Stock int `json:"stock"` internal string}
func main() { t := reflect.TypeFor[Product]() for i := 0; i < t.NumField(); i++ { f := t.Field(i) if f.IsExported() { fmt.Println(f.Name, f.Tag.Get("json")) } }}NumField and Field inspect direct fields of a struct type. IsExported distinguishes public fields. Tag.Get returns an empty string for both absent and explicitly empty values; Lookup distinguishes those cases. A tag does not automatically rename a Go field. Libraries such as encoding/json define their own tag interpretation.
Expected output:
Name nameStock stockInspect the method set
package main
import ( "fmt" "reflect")
type Meter struct{}
func (Meter) Read() int { return 1 }func (*Meter) Reset() {}func main() { t := reflect.TypeFor[Meter]() p := reflect.TypeFor[*Meter]() _, a := t.MethodByName("Reset") _, b := p.MethodByName("Reset") fmt.Println(t.NumMethod(), p.NumMethod(), a, b)}For non-interface types reflection exposes exported methods. A pointer type includes methods with value and pointer receivers; a value type includes value-receiver methods. Use an interface for actual calls when a method contract is known. Dynamic MethodByName and Call require signature checks and can panic on incompatible arguments.
Expected output:
1 2 false trueTry it locally
Use Lookup to distinguish an empty label tag from an absent tag. Print the two presence flags.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Reflection and unsafe 03: Inspect struct fields, tags and methods
Check the lesson objective before moving on.
What gives a json tag its meaning?
Which distinguishes an absent tag from an empty tag?