๐ŸŽ“ A1Learner
๐Ÿ”
0 of 28 lessons completed

Go Struct Reflection

Struct reflection reads the fields of a struct while the program runs. It reports each field name, each field type, and the tags on each field.

Fields in order

NumField sets the count for the loop. Field(i) reaches each field in order.

package main

import (
	"fmt"
	"reflect"
)

type Book struct {
	Title  string `json:"title"`
	Pages  int    `json:"pages"`
	Author string `json:"author"`
}

func main() {
	t := reflect.TypeOf(Book{})
	for i := 0; i < t.NumField(); i++ {
		f := t.Field(i)
		fmt.Println(f.Name, f.Type)
	}
}

Reading json tags

Each field carries a json tag from its definition. Tag.Get reads the key that the tag stores.

package main

import (
	"fmt"
	"reflect"
)

type Book struct {
	Title  string `json:"title"`
	Pages  int    `json:"pages"`
	Author string `json:"author"`
}

func main() {
	t := reflect.TypeOf(Book{})
	for i := 0; i < t.NumField(); i++ {
		fmt.Println(t.Field(i).Tag.Get("json"))
	}
}

Finding one field

FieldByName takes a field name as a string. It returns the field so its value can be read.

package main

import (
	"fmt"
	"reflect"
)

type Book struct {
	Title  string `json:"title"`
	Pages  int    `json:"pages"`
	Author string `json:"author"`
}

func main() {
	b := Book{Title: "Go", Pages: 120, Author: "Ana"}
	v := reflect.ValueOf(b)
	fmt.Println(v.FieldByName("Pages").Int())
	fmt.Println(v.FieldByName("Author").String())
}

Example

package main

import (
	"fmt"
	"reflect"
)

type User struct {
	Name  string `json:"name"`
	Email string `json:"email"`
	Age   int    `json:"age"`
}

func keys(v any) {
	t := reflect.TypeOf(v)
	for i := 0; i < t.NumField(); i++ {
		fmt.Println(t.Field(i).Tag.Get("json"))
	}
}

func main() {
	keys(User{})
}

Key points

  • NumField reports the number of fields in a struct type.
  • Field(i) returns one field record in declaration order.
  • A field record carries the field name and the field type.
  • Tag.Get reads the value stored under one tag key.
  • FieldByName finds a field record from its name.

In this example, keys takes a value of any type. It walks the fields of the struct type in order. It prints the json key from each field tag.

Note

Field order follows the order in the struct definition.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Go Playground

Exercise

Which call reads the json key stored on a field?