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

12 go

我有一个功能:

func ReturnTuples(map_ map[interface{}]interface{}) [][]interface{} {
Run Code Online (Sandbox Code Playgroud)

我试图像这样打电话:

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

但我得到了

cannot use m (type map[string]int) as type map[interface {}]interface {} in argument to ReturnTuples
Run Code Online (Sandbox Code Playgroud)

如果不是因为工作,stringint都实现interface{}

我搜索过,我能找到的最好的是将map [interface {}] interface {}转换为map [string]字符串,但它不会回答为什么我不能m用作参数.

我也相信,如果函数的参数只是interface{}它也可以工作,因为map[something][something]工具interface,对吧?最好的方法是什么,以及为什么它不适用于我的情况?

Blu*_*Bot 7

解决您的问题,只需将映射作为空接口的空接口启动:

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

然后你可以在'ReturnTuples'函数中指定你想要的任何类型键或值.

操场的例子

注意:请记住,如果您希望稍后将这些值用作原始类型,则需要使用类型断言,因为它们现在属于类型 interface{}

你可以这样做,这anything是一个你可以使用for循环得到的地图值:

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")
}
Run Code Online (Sandbox Code Playgroud)

如果你正在寻找"为什么" @ymonad给出完整答案的解释, 所以我不会再重复一次.

希望它有意义

PS:不要对这个问题进行投票,这是我眼中的合法选票......