Skip to content

Instantly share code, notes, and snippets.

@dolmen
Created November 2, 2017 18:12
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 dolmen/42eb18943feb5912b57fb2f0c255bbcd to your computer and use it in GitHub Desktop.
Save dolmen/42eb18943feb5912b57fb2f0c255bbcd to your computer and use it in GitHub Desktop.
StructIntMap
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