Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to search for an element in a golang slice

Tags:

slice

struct

go

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"?

like image 888
codec Avatar asked Jul 29 '16 08:07

codec


People also ask

How do you check if a slice contains an element in Go?

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.

How do I search for a string in Golang?

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.

How do you check if a slice contains a string Golang?

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.

How do you check if an element is in an array Golang?

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.


1 Answers

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 } 
like image 123
icza Avatar answered Sep 21 '22 09:09

icza