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

类型为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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序