Go does not provide a language construct or a standard library function to check whether a given value is in a slice. 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.
package main
import "fmt"
func contains(elems []string, v string) bool {
for _, s := range elems {
if v == s {
return true
}
}
return false
}
func main() {
fmt.Println(contains([]string{"a", "b", "c"}, "b"))
fmt.Println(contains([]string{"a", "b", "c"}, "d"))
}
Output:
true
false
If you want to operate on a slice of a different type, you must implement a separate function. For example, for int64
, the function would look like this:
func contains(elems []int64, v int64) bool {
for _, s := range elems {
if v == s {
return true
}
}
return false
}
This function works well if your slice is not too large. For longer lists of data, you should consider using a map for storage, which has generally much better lookup performance than iterating over slices.
Go Programming Language Specification does not make any complexity guarantees but in general map lookup should have a complexity of O(1), while finding an element in a slice is O(n).