问题描述
我在键入嵌套地图时遇到了一个非常奇怪的问题.
I'm experiencing a very strange problem with typed nested maps.
gore version 0.2.6 :help for help
gore> type M map[string]interface{}
gore> m := M{"d": M{}}
main.M{"d":main.M{}}
gore> m["d"]["test"] = "will fail"
# command-line-arguments
/tmp/288178778/gore_session.go:13:8: invalid operation: m["d"]["test"] (type interface {} does not support indexing)
/tmp/288178778/gore_session.go:14:17: invalid operation: m["d"]["test"] (type interface {} does not support indexing)
error: exit status 2
exit status 2
gore> m["e"] = "this works"
"this works"
gore> m
main.M{"d":main.M{}, "e":"this works"}
我做错了什么?为什么仅由于将地图嵌套在地图中而突然失败?
What am I doing wrong? Why does this suddenly fail just because the map is nested inside a map?
推荐答案
让我们来看看:
foo:=map[string]interface{}{}
定义 map [string] interface {}
时,可以设置所需的任何类型(满足空接口 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
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.
这篇关于类型为嵌套的map [string] interface {}的映射返回"type interface {}不支持索引".的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!