Cookies management by TermsFeed Cookie Consent

🔍 'Slice contains' function using Generics in Go

introduction generics generics-intro

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

Thank you for being on our site 😊. If you like our tutorials and examples, please consider supporting us with a cup of coffee and we'll turn it into more great Go examples.

Have a great day!

Buy Me A Coffee

🫘 Count the occurrences of an element in a slice in Go

Learn how to count elements in a slice that meet certain conditions
introduction generics generics-intro

🗑️ 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