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"
?
You can use
sort.Slice()
plussort.Search()
See: https://play.golang.org/p/47OPrjKb0g_c
With a simple
for
loop: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:Notes:
It depends on your case whether multiple configs may exist with the same
key
, but if not, you shouldbreak
out of the loop if a match is found (to avoid searching for others).Also if this is a frequent operation, you should consider building a
map
from it which you can simply index, e.g.There is no library function for that. You have to code by your own.
Working code: https://play.golang.org/p/IJIhYWROP_
You can save the struct into a map by matching the struct
Key
andValue
components to their fictive key and value parts on the map:Then using the golang comma ok idiom you can test for the key presence: