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?
Let's take this :
foo:=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{}
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)
}
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.