Getting the key type is easy:
reflect.TypeOf(any).Key()
In order to do the whole conversion, you need to create a value of a type map map[keyType]interface{}, and then copy the values. The following is a working example of how this can be done:
package main
import (
"errors"
"fmt"
"reflect"
)
func InterfaceMap(i interface{}) (interface{}, error) {
t := reflect.TypeOf(i)
switch t.Kind() {
case reflect.Map:
v := reflect.ValueOf(i)
it := reflect.TypeOf((*interface{})(nil)).Elem()
m := reflect.MakeMap(reflect.MapOf(t.Key(), it))
for _, mk := range v.MapKeys() {
m.SetMapIndex(mk, v.MapIndex(mk))
}
return m.Interface(), nil
}
return nil, errors.New("Unsupported type")
}
func main() {
foo := make(map[string]int)
foo["anisus"] = 42
bar, err := InterfaceMap(foo)
if err != nil {
panic(err)
}
fmt.Printf("%#v\n", bar.(map[string]interface{}))
}
Conclusion:
map[string]interface {}{"anisus":42}
Playground: http://play.golang.org/p/tJTapGAs2b
source
share