Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert interface to its respecting map

Tags:

reflection

go

For example if I have an interface{} value that originally a map[string]map[int64][]int64 or any other kind of map, how to get the key type of the map? or more precise, how to convert it to map[theKeyType]interface{}?

func Transverse(any interface{}) string {
  res := ``
  switch any.(type) {
    case string:
      return ``
    case []byte:
      return ``
    case int, int64, int32:
      return ``
    case float32, float64:
      return ``
    case bool:
      return ``
    case map[int64]interface{}:
      return ``
    case map[string]interface{}:
      return ``
    case []interface{}:
      return ``
    default:
      kind := reflect.TypeOf(any).Kind()
      switch kind {
      case reflect.Map:
        // how to convert it to map[keyType]interface{} ?
      }
      return `` // handle other type
   }
   return ``
}
like image 221
Kokizzu Avatar asked Jan 23 '15 08:01

Kokizzu


1 Answers

Getting the Key type is easy:

reflect.TypeOf(any).Key()

To make the entire conversion, you need to create a map value of type map[keyType]interface{} and then copy the values over. Below is a working example how this can be done:

package main

import (
    "errors"
    "fmt"
    "reflect"   
)

func InterfaceMap(i interface{}) (interface{}, error) {
    // Get type
    t := reflect.TypeOf(i)

    switch t.Kind() {
    case reflect.Map:
        // Get the value of the provided map
        v := reflect.ValueOf(i)

        // The "only" way of making a reflect.Type with interface{}
        it := reflect.TypeOf((*interface{})(nil)).Elem()

        // Create the map of the specific type. Key type is t.Key(), and element type is it
        m := reflect.MakeMap(reflect.MapOf(t.Key(), it))

        // Copy values to new map
        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{}))
}

Output:

map[string]interface {}{"anisus":42}

Playground: http://play.golang.org/p/tJTapGAs2b

like image 111
ANisus Avatar answered Nov 20 '22 02:11

ANisus