我有一片结构。
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}]
我如何搜索此数组以获取元素 where key="key1"
?
原文由 codec 发布,翻译遵循 CC BY-SA 4.0 许可协议
从添加泛型支持的 Go 1.18 开始,有一个
golang.org/x/exp/slices
包,其中包含一个名为slices.IndexFunc()
的通用“查找”函数:for _, v := range myconfig { if v.Key == “key1” { // Found! } }
for i := range myconfig { if myconfig[i].Key == “key1” { // Found! } }
for i := range myconfig { if myconfig[i].Key == “key1” { // Found! break } }
// 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 }
”`