liveBook · Manning

Reflect.StructField

As explained in Go in Practice, Second Edition

reflect.StructField is a Go reflection descriptor containing metadata about a field declared in a struct type.

reflect.StructField describes a field declared in a struct type. It provides metadata such as the field name and data type, but not the field's runtime value. section 13.1.3

Use the type and value APIs together when examining struct fields:

  • Obtain a reflect.Type from the value and confirm that its kind is reflect.Struct. section 13.1.3
  • Call Type.NumField() to determine how many fields exist, then Type.Field(index) to obtain each reflect.StructField. section 13.1.3
  • Read metadata through the StructField, and retrieve the corresponding runtime value with Value.Field(index). section 13.1.3
  • Apply reflect.Indirect() when a field contains a pointer and inspection should continue at the pointed-to value. section 13.1.3

Walking nested fields

A recursive walker can enumerate a Person struct, report fields such as Name and Address, and then follow their pointers to inspect Name and Address fields. section 13.1.3

Listing 13.6 Types to examine
package main

import (
     "fmt"
     "reflect"
     "strings"
)

type MyInt int
type Person struct {
     Name    *Name
     Address *Address
}
type Name struct {
     Title, First, Last string
}
type Address struct {
     Street, Region string
}

Use the related type definitions to trace how reflect.StructField metadata describes pointer fields and nested structs. section 13.1.3

How Go in Practice, Second Edition covers it

How deep it goes
Explains field metadata, indexed type-value access, and pointer traversal through reflect.Indirect.
Examples
Uses a recursive walker over Person, Name, Address, a simple struct, and a defined integer type.
What it assumes
Distinguishes reflection types from values while starting with values obtained through reflect.ValueOf.
What you can do after
Apply it via Go reflection to enumerate struct fields and inspect corresponding runtime values.
How it connects
Connects reflect.Type, Type.NumField, Type.Field, reflect.Value, Value.Field, reflect.Indirect, and structs.

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.