Cookies management by TermsFeed Cookie Consent
Russia has invaded Ukraine and already killed tens of thousands of civilians, with many more raped or tortured. It's a genocide. We need your help. Let's fight back against the Russian regime.
Help Ukraine! Fight the Russian regime!

🔍 'Slice contains' function using Generics in Go

introduction generics generics-intro

Please consider supporting us by disabling your ad blocker

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.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
package main

import "fmt"

func contains[T comparable](elems []T, v T) 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([]int{1, 2, 3}, 2))
    fmt.Println(contains([]int{1, 2, 3}, 10))
}

Along with the Go 1.18 release, the golang.org/x/exp/slices package has also been released, with the Contains() 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

🗑️ Remove duplicates from any slice using Generics in Go

Learn how to create a slice with unique values using Generics
introduction slice generics generics-intro

🔉 Reduce function using Generics in Go

Learn how to define a function to accumulate slice values using Generics
introduction generics generics-intro

🦾 Create a slice 'map' function using Generics in Go

Learn how to apply a function to all slice elements using Generics
introduction generics generics-intro