Created
November 2, 2017 18:12
-
-
Save dolmen/42eb18943feb5912b57fb2f0c255bbcd 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 main | |
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