Inspecting Struct Fields and Tags
Iterating fields and reading struct tags
Inspecting Struct Fields and Tags is a free Go Academy lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Go Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
StructField type
reflect.StructField describes one field of a struct: Name, Type, Tag, Index, Offset, Anonymous, and IsExported.
Iterating fields
Loop over all fields of a struct type:
t := reflect.TypeOf(struct{ ID int; Name string }{})
for i := 0; i < t.NumField(); i++ {
f := t.Field(i)
fmt.Println(f.Name, f.Type, f.IsExported())
}Reading struct tags
Tags are accessed via StructField.Tag.Get("key"):
type User struct {
ID int `json:"id" db:"user_id"`
Name string `json:"name,omitempty"`
}
f, _ := reflect.TypeOf(User{}).FieldByName("Name")
fmt.Println(f.Tag.Get("json")) // "name,omitempty"Parsing tag options
Tags may contain comma-separated options. Parse them with strings.Split:
tag := f.Tag.Get("json") // "name,omitempty"
parts := strings.Split(tag, ",")
name := parts[0] // "name"
omitempty := len(parts) > 1 && parts[1] == "omitempty"FieldByName and FieldByIndex
Look up a field by name or index. FieldByName searches exported fields in the struct and embedded structs:
f, ok := reflect.TypeOf(User{}).FieldByName("Name")
if ok { fmt.Println(f.Tag.Get("json")) }Embedded struct fields
For embedded structs, Anonymous is true. Use Type.FieldByIndex([]int{0,1}) to access nested fields.
Unexported fields
Unexported (lowercase) fields can be inspected for their type and tag but their values cannot be read or set via reflection — a panic results.
Building a field cache
Parsing struct tags on every call is expensive. Cache the result in a sync.Map keyed by reflect.Type:
var fieldCache sync.Map
func getFields(t reflect.Type) []fieldInfo {
if v, ok := fieldCache.Load(t); ok { return v.([]fieldInfo) }
fields := parseFields(t)
fieldCache.Store(t, fields)
return fields
}Use case: simple ORM
Walk all fields with a "db" tag to build an INSERT column list dynamically:
t := reflect.TypeOf(u)
v := reflect.ValueOf(u)
for i := 0; i < t.NumField(); i++ {
col := t.Field(i).Tag.Get("db")
val := v.Field(i).Interface()
// build query...
}Use case: config loader
Walk struct fields with an "env" tag and populate them from environment variables:
if env := f.Tag.Get("env"); env != "" {
if val := os.Getenv(env); val != "" {
v.Field(i).SetString(val)
}
}StructTag.Lookup
Tag.Lookup("key") returns the tag value and a boolean indicating whether the key was present at all (unlike Get, which returns "" for absent keys).
val, ok := f.Tag.Lookup("json")
if !ok { /* no json tag */ }Quick Check
How do you read the value of the "json" struct tag from a reflect.StructField?
Recap: Struct Fields and Tags
Key points:
- reflect.TypeOf → .NumField(), .Field(i) for field metadata
- StructField.Tag.Get("key") to read tag values
- Cache field metadata in sync.Map to avoid repeated parsing
- Use Tag.Lookup when absent tag vs empty string matters
Frequently asked questions
Is the “Inspecting Struct Fields and Tags” lesson free?
Yes — the full text of “Inspecting Struct Fields and Tags” is free to read here on the web, and the Go Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Go Academy course, upgrade to CoddyKit PRO.
What will I learn in “Inspecting Struct Fields and Tags”?
Iterating fields and reading struct tags You practise Go Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Go Academy?
No prior experience is required. Go Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Inspecting Struct Fields and Tags” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Go Academy lesson?
Yes. Every Go Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- reflect.Type and reflect.Value
- Inspecting Struct Fields and Tags
- Dynamic Function Calls
- Practical Reflection: Serializers