How to Check If a Slice Contains an Element in Go
The Go 1.21 stable release in August 2023
introduced a new slices
package, featuring generic functions applicable to any
slice type. A key function, Contains()
, checks for the presence of an element
in a slice:
func Contains[S ~[]E, E comparable](s S, v E) bool
This function takes a slice and an element to check, returning a boolean indicating the element’s presence. Here’s an example of its usage:
package main
import (
"slices"
)
func main() {
numbers := []int{0, 42, 10, 8}
containsTen := slices.Contains(numbers, 10) // true
containsTwo := slices.Contains(numbers, 2) // false
}
Using the x/exp/slices package (Go 1.18 to 1.20)
Before Go 1.21, the experimental x/exp/slices package provided similar functionality. Install it first, then use it like this:
go get golang.org/x/exp/slices
package main
import (
"golang.org/x/exp/slices"
)
func main() {
numbers := []int{0, 42, 10, 8}
containsTen := slices.Contains(numbers, 10) // true
containsTwo := slices.Contains(numbers, 2) // false
}
Go 1.17 and earlier
Since Go 1.17 and earlier releases do not support generics, you need a custom
function for each slice type. For example, here’s a contains
function for
string slices:
// 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", "Christine", "Mike"}
fmt.Println(contains(s, "James")) // true
fmt.Println(contains(s, "Jack")) // false
}
In the contains()
function, each element of the string slice is compared to
the specified string (second parameter). The function returns true
and exits
if a match is found; if not, it returns false
.
With the release of Go 1.18 and particularly Go 1.21, the need to write custom
functions like contains
is eliminated. Upgrading to these newer versions is
highly recommended to take advantage of these improvements.
Thanks for reading, and happy coding!