Created
September 15, 2019 06:01
-
-
Save Natata/b79add69f68614c88c069417bffff441 to your computer and use it in GitHub Desktop.
travel all fields and tags of struct
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
usage