douzhao7445 2016-07-29 08:46
浏览 1501
已采纳

如何在golang切片中搜索元素

I have a slice of structs.

type Config struct {
    Key string
    Value string
}

// I form a slice of the above struct
var myconfig []Config 

// unmarshal a response body into the above slice
if err := json.Unmarshal(respbody, &myconfig); err != nil {
    panic(err)
}

fmt.Println(config)

Here is the output of this:

[{key1 test} {web/key1 test2}]

How can I search this array to get the element where key="key1"?

  • 写回答

4条回答 默认 最新

  • duande3134 2016-07-29 08:49
    关注

    With a simple for loop:

    for _, v := range myconfig {
        if v.Key == "key1" {
            // Found!
        }
    }
    

    Note that since element type of the slice is a struct (not a pointer), this may be inefficient if the struct type is "big" as the loop will copy each visited element into the loop variable.

    It would be faster to use a range loop just on the index, this avoids copying the elements:

    for i := range myconfig {
        if myconfig[i].Key == "key1" {
            // Found!
        }
    }
    

    Notes:

    It depends on your case whether multiple configs may exist with the same key, but if not, you should break out of the loop if a match is found (to avoid searching for others).

    for i := range myconfig {
        if myconfig[i].Key == "key1" {
            // Found!
            break
        }
    }
    

    Also if this is a frequent operation, you should consider building a map from it which you can simply index, e.g.

    // Build a config map:
    confMap := map[string]string{}
    for _, v := range myconfig {
        confMap[v.Key] = v.Value
    }
    
    // And then to find values by key:
    if v, ok := confMap["key1"]; ok {
        // Found
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 phython如何实现以下功能?查找同一用户名的消费金额合并—
  • ¥15 孟德尔随机化怎样画共定位分析图
  • ¥18 模拟电路问题解答有偿速度
  • ¥15 CST仿真别人的模型结果仿真结果S参数完全不对
  • ¥15 误删注册表文件致win10无法开启
  • ¥15 请问在阿里云服务器中怎么利用数据库制作网站
  • ¥60 ESP32怎么烧录自启动程序
  • ¥50 html2canvas超出滚动条不显示
  • ¥15 java业务性能问题求解(sql,业务设计相关)
  • ¥15 52810 尾椎c三个a 写蓝牙地址