Inspecting Struct Fields and Tags
Iterating fields and reading struct tags
Inspecting Struct Fields and Tags is a free Go Academy lesson on CoddyKit. This is lesson 2 of 4. Any 3 lessons of this learning path are free to read in full — after that, CoddyKit PRO unlocks every lesson, plus hands-on practice with a built-in code editor and a 24/7 AI tutor. It is part of the Go Academy learning path, and your progress syncs across the web and the CoddyKit app. The Go Academy course includes 4 lessons in total.
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
Learn Go with an AI tutor — free
Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.
- Courses
- 51
- Lessons
- 203
Frequently Asked Questions
Is the “Inspecting Struct Fields and Tags” lesson free?
Yes — any 3 lessons of the Go Academy learning path, including “Inspecting Struct Fields and Tags”, are free to read in full here on the web. After that, CoddyKit PRO unlocks every lesson, plus interactive practice with a built-in code editor and a 24/7 AI tutor. The Go Academy course includes 4 lessons in total.
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, so you can start here or from the beginning and move at your own pace. This is lesson 2 of 4.
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