How to search for an element in a golang slice
Starting with Go 1.18 which adds generics support, there's a golang.org/x/exp/slices
package which contains a generic "find" function named slices.IndexFunc()
:
func IndexFunc[E any](s []E, f func(E) bool) int
IndexFunc returns the first index i satisfying f(s[i]), or -1 if none do.
Using that:
idx := slices.IndexFunc(myconfig, func(c Config) bool { return c.Key == "key1" })
Try it on the Go Playground.
Prior to Go 1.18 and for a faster alternative, read on:
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
}
There is no library function for that. You have to code by your own.
for _, value := range myconfig {
if value.Key == "key1" {
// logic
}
}
Working code: https://play.golang.org/p/IJIhYWROP_
package main
import (
"encoding/json"
"fmt"
)
func main() {
type Config struct {
Key string
Value string
}
var respbody = []byte(`[
{"Key":"Key1", "Value":"Value1"},
{"Key":"Key2", "Value":"Value2"}
]`)
var myconfig []Config
err := json.Unmarshal(respbody, &myconfig)
if err != nil {
fmt.Println("error:", err)
}
fmt.Printf("%+v\n", myconfig)
for _, v := range myconfig {
if v.Key == "Key1" {
fmt.Println("Value: ", v.Value)
}
}
}
You can use sort.Slice()
plus sort.Search()
type Person struct {
Name string
}
func main() {
crowd := []Person{{"Zoey"}, {"Anna"}, {"Benni"}, {"Chris"}}
sort.Slice(crowd, func(i, j int) bool {
return crowd[i].Name <= crowd[j].Name
})
needle := "Benni"
idx := sort.Search(len(crowd), func(i int) bool {
return string(crowd[i].Name) >= needle
})
if idx < len(crowd) && crowd[idx].Name == needle {
fmt.Println("Found:", idx, crowd[idx])
} else {
fmt.Println("Found noting: ", idx)
}
}
See: https://play.golang.org/p/47OPrjKb0g_c
You can save the struct into a map by matching the struct Key
and Value
components to their fictive key and value parts on the map:
mapConfig := map[string]string{}
for _, v := range myconfig {
mapConfig[v.Key] = v.Value
}
Then using the golang comma ok idiom you can test for the key presence:
if v, ok := mapConfig["key1"]; ok {
fmt.Printf("%s exists", v)
}