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 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘