How to check if a slice contains an element in Go
There is no built-in method to check if a slice or array contains an item in Go. But don’t worry, it’s easy enough to write one yourself.
Sometimes, you just want to know if an element is present in a slice. While this is a fairly common need, Go does not provide generic method for this purpose so you need to write your own function to do it. Don’t fret, I’ve got you covered. Here’s all you need to add this functionality to your programs:
// https://play.golang.org/p/Qg_uv_inCek
// contains checks if a string is present in a slice
func contains(s []string, str string) bool {
for _, v := range s {
if v == str {
return true
}
}
return false
}
func main() {
s := []string{"James", "Wagner", "Christene", "Mike"}
fmt.Println(contains(s, "James")) // true
fmt.Println(contains(s, "Jack")) // false
}
The contains
function above iterates over the string slice and compares each value to the string from the second parameter. If the value is found, true
is returned and the function exits. Otherwise, if the value is not found, false
is returned.
While this function works well enough, it may be inefficient for larger slices. In such cases, consider using a map instead of a slice as you won’t have to iterate over the entire list just to check for the existence of a value.
Thanks for reading, and happy coding!