Checking if an array contains a given value is a popular programming function implemented natively in many programming languages. In Go, we have to implement it ourselves, but thanks to the new Generics feature, we can write a single contains()
function that will work for slices of any type whose values can be compared.
If you want to see how to write the
contains()
function without Generics, that only works for string slices, check one of our previous tutorials here.
This article is part of the Introduction to Go Generics series. Go here to see more.
|
|
Along with the Go 1.18 release, the
golang.org/x/exp/slices
package has also been released, with theContains()
function working the same as the one above.
As you already know from our previous Generics tutorial, the type parameters of the generic functions are declared in square brackets after the function name. In the contains()
, we use the T
type parameter with the comparable
constraint. It is a built-in constraint that describes any type whose values can be compared, i.e., we can use ==
and !=
operators on them. The function body is really simple and does not differ from the non-generic version. We iterate over the elems
slice and check if the current value is the value v
we are looking for. This way, we get a function that can operate on any slice type.
Output of the main()
function:
true
true
false