且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

类型为嵌套的map [string] interface {}的映射返回"type interface {}不支持索引".

更新时间:2021-09-08 23:24:02

让我们来看看:

foo:=map[string]interface{}{}

定义 map [string] interface {} 时,可以设置所需的任何类型(满足

When you define a map[string]interface{}, you can set any type you want (any type that fulfill the empty interface interface{} contract a.k.a any type) for a given string index.

foo["bar"]="baz"
foo["baz"]=1234
foo["foobar"]=&SomeType{}

但是当您尝试访问某些键时,您没有得到任何int,字符串或任何自定义结构,而是得到了 interface {}

But when you try to access some key, you don't get some int, string or any custom struct, you get an interface{}

var bar string = foo["bar"] // error

为了将 bar 视为字符串,您可以创建类型断言类型切换.

in order to treat bar as an string, you can make a type assertion or a type switch.

在这里我们进行类型断言(实时示例):

Here we go for the type assertion (live example) :

if bar,ok := foo["bar"].(string); ok {
   fmt.Println(bar)
}

但是正如@Volker所说的,作为一个初学者,***采取旅行的旅程以更熟悉这些概念.

But as @Volker said, it is a good idea -as a beginner- to take the tour of go to get more familiar with such concepts.