Skip to content

Instantly share code, notes, and snippets.

@Natata
Created September 15, 2019 06:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Natata/b79add69f68614c88c069417bffff441 to your computer and use it in GitHub Desktop.
Save Natata/b79add69f68614c88c069417bffff441 to your computer and use it in GitHub Desktop.
travel all fields and tags of struct
func TravelStruct(v interface{}, f func(fieldName string, tag reflect.StructTag)) {
travelStruct(reflect.ValueOf(v).Type(), f)
}
func travelStruct(t reflect.Type, f func(fieldName string, tag reflect.StructTag)) {
t = PtrToType(t)
if t.Kind() != reflect.Struct {
return
}
for i := 0; i < t.NumField(); i++ {
field := t.Field(i)
f(field.Name, field.Tag)
fieldType := t.Field(i).Type
fieldType = PtrToType(fieldType)
if fieldType.Kind() == reflect.Struct {
travelStruct(fieldType, f)
}
}
}
// PtrToType try to get the real value of the type point to
func PtrToType(t reflect.Type) reflect.Type {
for t.Kind() == reflect.Ptr {
t = t.Elem()
}
return t
}
@Natata
Copy link
Author

Natata commented Sep 15, 2019

usage


import (
    "fmt"
    "reflect"
)

type A struct {
    I int    `json:"test_i"`
    M string `json:"test_m"`
    *B
}

type B struct {
    N string `json:"test_n"`
    I int    `json:"test_i_in_b"`
}

func main() {
    a := &A{ 
        I: 1,
        M: "taaaa",
        B: &B{ 
            N: "OKOKOK",
            I: 123,
        },  
    }   

    TravelStruct(a, func(fieldName string, tag reflect.StructTag) {
        fmt.Println("field name: ", fieldName)
        fmt.Println("tag: ", tag.Get("json"))
    })  
    fmt.Println("Hello, playground")
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment