douzhantao2857 2015-01-23 08:14
浏览 15
已采纳

将接口转换为其尊重地图

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 ``
}
  • 写回答

1条回答 默认 最新

  • dpa31905 2015-01-23 10:27
    关注

    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
    ", bar.(map[string]interface{}))
    }
    

    Output:

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

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 2024-五一综合模拟赛
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭