dongqing6661
2017-11-21 12:26
浏览 97
已采纳

类型为Map [String] interface {}的嵌套映射返回“类型接口{}不支持索引”

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?

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • duanhuiqing9528 2017-11-21 13:49
    已采纳

    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.

    已采纳该答案
    打赏 评论

相关推荐 更多相似问题