How to check if a slice contains an element in Go
Checking if a slice or array contains an item in Go is really easy as long as you’re using Go 1.18 or later.
The Go 1.21 release, which is scheduled for
August 2023, includes a new package called slices
.
This package provides a set of generic functions
that work with slices of any type. One of the most useful functions in the
slices package is Contains()
, which checks if an element of the slice is
present or not.
The Contains()
function takes two arguments: the first argument is the slice,
and the second argument is the element that you want to check for. The function
returns a boolean value, indicating whether or not the element is present in the
slice.
Here is an example of how to use this function in your Go programs:
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
The x/exp/slices package is an
experimental package initially released for Go 1.18 and later developed into the
slices
package in Go 1.21. While it does not provide all the functionality in
the final slices
package, the Contains()
function demonstrated above is
present and works the same way. You only need to install the package first:
go get golang.org/x/exp/slices
Then import it into your program like this:
package main
import (
"golang.org/x/exp/slices"
)
. . .
Go 1.17 and earlier
Since Go 1.17 and earlier releases do not support generics, you need to write your own function to check if a slice contains an element in Go. Unfortunately, you need to do this for each slice type that requires this functionality. Here’s an example showcasing how to implement this for a slice of strings:
// 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.
Fortunately, the release of Go 1.18 makes writing these functions unnecessary, so ensure that you upgrade to the latest version as soon as possible.
Thanks for reading, and happy coding!