duanliaogui4133 2017-02-23 10:45
浏览 758
已采纳

使用map [string] int作为map [interface {}] interface {}类型的参数

I have a function:

func ReturnTuples(map_ map[interface{}]interface{}) [][]interface{} {

In which I'm trying to call like this:

m := make(map[string]int)
m["k1"] = 7
m["k2"] = 13
fmt.Println(ReturnTuples(m))

But I'm getting

cannot use m (type map[string]int) as type map[interface {}]interface {} in argument to ReturnTuples

Shouldn't it work since string and int both implement interface{}?

I've searched and the best I could find was Convert map[interface {}]interface {} to map[string]string but it won't answer why I cannot use m as an argument.

I also believe that if the argument of the function were only interface{} it would work too, since map[something][something] implements interface, right? What is the best way to do it, and why it won't work in my case?

  • 写回答

2条回答 默认 最新

  • dongtan6336 2017-02-23 16:09
    关注

    A solution to your problem, simply initiate the map as an empty interface of empty interfaces:

    m := map[interface{}]interface{}

    then you can assign any type key or value you want in the 'ReturnTuples' function.

    playground example

    NOTE: remember that if you want to use the values later as the original types, you will need to use type assertion because now they are of type interface{}

    You may do something this like this, were anything is one map value which you can get using a for loop:

    switch v := anything.(type) {
          case string:
                fmt.Println(v)
          case int32, int64:
                fmt.Println(v)
          case string:
                fmt.Println(v)
          case SomeCustomType:
                fmt.Println(v)
          default:
                fmt.Println("unknown")
    }
    

    If you are looking for an explanation for the "why" @ymonad gave a full answer so I wont repeat it again.

    hope it make sense

    PS: don't get the down votes on the question, a legit one in my eyes...

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛