Created
June 13, 2018 10:20
-
-
Save dolmen/ebb53d6d6ae37ee82cad0f53e937dd80 to your computer and use it in GitHub Desktop.
StructIntMap
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
package structintmap | |
import "reflect" | |
func StructIntMap(value interface{}) map[string]int { | |
m := make(map[string]int) | |
structIntMap(reflect.ValueOf(value), m, "") | |
return m | |
} | |
func fieldPath(path, name string) string { | |
if len(path) == 0 { | |
return name | |
} | |
return path + "." + name | |
} | |
func structIntMap(st reflect.Value, m map[string]int, path string) { | |
if st.Kind() == reflect.Ptr { | |
st = st.Elem() | |
} | |
t := st.Type() | |
for i := 0; i < t.NumField(); i++ { | |
field := t.Field(i) | |
switch field.Type.Kind() { | |
case reflect.Ptr: | |
if st.Field(i).IsNil() { | |
break | |
} | |
fallthrough | |
case reflect.Struct: | |
structIntMap(st.Field(i), m, fieldPath(path, field.Name)) | |
case reflect.Int: | |
m[fieldPath(path, field.Name)] = int(st.Field(i).Int()) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment