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"
?
How to check if a slice contains an element. To check if a particular element is present in a slice object, we need to perform the following steps: Use a for loop to iterate over each element in the slice . Use the equality operator ( == ) to check if the current element matches the element you want to find.
You can search a particular text/string/character within a string by using Contains(). It returns output either true or false. If string 1 found in string 2 then it returns true. If string 1 is not found in string 2 then it returns false.
To do this, you need to write your own contains() function that takes two arguments: the slice and the element to find. As a result, it should return true if the slice contains this element and false otherwise.
To determine if a specific element exist in an array, we need to iterate each array element using for loop and check using if condition.
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 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With