douyan4900 2019-01-16 17:30
浏览 64
已采纳

在map [string] interface {}中检查多个键时使用OR逻辑

I have a map[string]interface{} called mapped:

mapped map[stringinterface{}

I want to iterate through it checking to see if either of these keys exist:

  • columns
  • rows

Then if so, I want to append the row or column to a slice of strings called:

  • columnOrRowArray

I understand that if I just needed to find, for example columns, within mapped I can do this:

var columnOrRowArray []string

if columnsOrRows, ok := mapped["columns"].([]interface{}); ok {
    for _, columnOrRow := range columnsOrRows {
        if columnOrRowValueIsString, ok = columnOrRow.(string); ok {
            columnOrRowArray = append(columnOrRowArray, columnOrRowValueIsString)
        }
    }
}

What would be a clean way without me duplicating the above for using row logic for the mapped["rows"]?

I want to do something that is basically this:

columnsOrRows, ok := mapped["columns"].([]interface{}) || mapped["rows"].([]interface{}); ok {

So in plain English, "if mapped has a the column or row key, assign to variable columnsOrRows"

Obviously I know the syntax for that is wrong, but I can't find an example of someone doing this

  • 写回答

1条回答 默认 最新

  • douchi0638 2019-01-16 17:39
    关注

    Test for both keys:

    columnsOrRows, ok := mapped["columns"].([]interface{})
    if !ok {
        columnsOrRows, ok = mapped["rows"].([]interface{})
    }
    
    if ok {
        for _, columnOrRow := range columnsOrRows {
            if columnOrRowValueIsString, ok = columnOrRow.(string); ok {
                columnOrRowArray = append(columnOrRowArray, columnOrRowValueIsString)
            }
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 基于作物生长模型下,有限水资源的最大化粮食产量的资源优化模型建立
  • ¥15 生成的QRCode圖片加上下載按鈕
  • ¥15 板材切割优化算法,数学建模,python,lingo
  • ¥15 科来模拟ARP欺骗困惑求解
  • ¥100 iOS开发关于快捷指令截屏后如何将截屏(或从截屏中提取出的文本)回传给本应用并打开指定页面
  • ¥15 unity连接Sqlserver
  • ¥15 图中这种约束条件lingo该怎么表示出来
  • ¥15 VSCode里的Prettier如何实现等式赋值后的对齐效果?
  • ¥15 流式socket文件传输答疑
  • ¥20 keepalive配置业务服务双机单活的方法。业务服务一定是要双机单活的方式