Skip to content

Instantly share code, notes, and snippets.

@Asterism12
Last active July 13, 2022 02:52
Show Gist options
  • Save Asterism12/2d46dcdc4e5f7f30574ce8b6a5740666 to your computer and use it in GitHub Desktop.
Save Asterism12/2d46dcdc4e5f7f30574ce8b6a5740666 to your computer and use it in GitHub Desktop.
how to traverse fields of struct in Go
package main
import (
"fmt"
"reflect"
)
type Msg struct {
Key string `json:"key"`
}
type MyStruct struct {
Name string `json:"name"`
Age int `json:"age"`
Msg Msg
}
func traverse() {
st := MyStruct{
Name: "hello",
Age: 12,
Msg: Msg{Key: "value"},
}
v := reflect.ValueOf(&st).Elem()
t := reflect.TypeOf(&st).Elem()
for i := 0; i < t.NumField(); i++ {
fmt.Println("tag ", t.Field(i).Tag.Get("json"))
fmt.Println("name ", t.Field(i).Name)
switch v.Field(i).Type().Kind() {
case reflect.String:
fmt.Println("string ", v.Field(i).String())
case reflect.Int:
fmt.Println("int ", v.Field(i).Int())
case reflect.Struct:
fmt.Println("struct addr ", v.Field(i).Addr().Interface())
// ... handle other case
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment