本问题已经有最佳答案,请猛点这里访问。

地图上的类型断言不起作用,这是正确的方法吗?

为了详细说明,我的目标是返回具有动态类型的地图。 此示例仅用于演示。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package main

import"fmt"

func main()  {
    m := hello().(map[string]int)
    fmt.Println(m)
}

func hello() interface{} {
    return map[string]interface{} {
       "foo": 2,
       "bar": 3,
    }
}

恐慌

panic: interface conversion: interface {} is map[string]interface {},
not map[string]int

  • 问题是什么? map[string]interface{}不是map[string]int,因此类型声明失败。
  • 我是否应该假设地图的键值为字符串,值的值为int? 使用其他类型的类型断言,然后使用这些假设进行映射
  • 您不能对不兼容的类型进行类型声明。 您必须手动将其转换。

返回适当的类型

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package main

import"fmt"

func main()  {
    m := hello().(map[string]int)
    fmt.Println(m)
}

func hello() interface{} {
    return map[string]int{
       "foo": 2,
       "bar": 3,
    }
}
  • 我不能随意返回静态类型,映射可以将任何类型作为键,将任何类型作为值。 现在为了演示,我已经将这些值视为接口。 我这样做对吗?
  • 因此您需要map [interface {}] interface {}
  • 是的,如果我现在可以找出map [string] interface {},我将在稍后看到第二部分。
  • Just to elaborate, my goal is to return a map with dynamic types暂时没有这样的事情。 但是,您可以使用interface {}来混合多种类型。
  • 我正在使用反射来实现这一目标。 与其他类型的作品,但与地图我得到这个错误。

为了回答我自己的问题,断言适用于地图值

一些例子

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
package main

import"fmt"

type person struct {
    name string
}

func main()  {
    m := example1().(map[string]interface{})

    fmt.Println(m["foo"].(int))

    m2 := example2().(map[string]interface{})

    fmt.Println(m2["foo"].(person).name)

}

func example1() interface{} {
    return map[string]interface{} {
       "foo": 2,
       "bar": 3,
    }
}

func example2() interface{} {
    m := make(map[string]interface{})

    m["foo"] = person{"Name is foo!"}
    m["bar"] = person{"Name is bar!"}

    return m
}