如何在golang切片中搜索元素 [英] How to search for an element in a golang slice

查看:115
本文介绍了如何在golang切片中搜索元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有片结构.

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)

这是此的输出:

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

如何搜索此数组以获取 key ="key1" 所在的元素?

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

推荐答案

带有简单的 for 循环:

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

请注意,由于切片的元素类型是 struct (而不是指针),所以如果struct type为"big",这可能效率不高,因为循环会将每个访问的元素复制到循环中变量.

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.

仅在索引上使用 range 循环会更快,这样可以避免复制元素:

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!
    }
}

注释:

这取决于您的情况,是否可能使用相同的 key 存在多个配置,但如果不存在,则如果找到匹配项,则应 break 退出循环避免寻找其他人.)

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
    }
}

如果这是一项经常性的操作,则应考虑从中构建一个 map ,您可以对其进行简单索引,例如

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
}

这篇关于如何在golang切片中搜索元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆