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条)

报告相同问题?

悬赏问题

  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 个人网站被恶意大量访问,怎么办
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制