dongxiezhi0590 2018-09-24 12:52
浏览 44
已采纳

如何在接口中迭代数组{}?

i have a map

myMap := make(map[string]interface{})

one of this map elements is array of []map[string]string

myMap["element"] = []map[string]string

how can i iterate this array?

  • 写回答

1条回答 默认 最新

  • duanmengmiezen8855 2018-09-24 12:55
    关注

    You can't iterate over a value of type interface{}, which is the type you'll get returned from a lookup on any key in your map (since it has type map[string]interface{}).

    You should use a type assertion to obtain a value of that type, over which you can then range.

    myElt := myMap["element"]
    v, ok := myElt.([]map[string]string)
    if !ok {
        // TODO: Handle the error
    }
    
    for i, item := range v {
        // TODO: do something with each map[string]string item in the slice
    }
    

    Here's a working playground example using a contrived setup for those map types.


    If you know the value is of the specified slice type, you can omit the ok check in the type assertion. This might be the case if you are using someone else's generic map implementation (which has keys of type interface{}) and know you only ever populate it with values of type []map[string]string. However, exercise caution: if you obtain a value not of this type from the map, and you omit the check, your program will panic.

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

报告相同问题?

悬赏问题

  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 AT89C51控制8位八段数码管显示时钟。
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题