Cookies management by TermsFeed Cookie Consent

🔎 Check if the slice contains the given value in Go

introduction slice

Go does not provide a language construct or a standard library function to check whether a given value is in a slice. To do this, you need to write your own contains() function that takes two arguments: the slice and the element to find. As a result, it should return true if the slice contains this element and false otherwise.

package main

import "fmt"

func contains(elems []string, v string) 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([]string{"a", "b", "c"}, "d"))
}

Output:

true
false

If you want to operate on a slice of a different type, you must implement a separate function. For example, for int64, the function would look like this:

func contains(elems []int64, v int64) bool {
    for _, s := range elems {
        if v == s {
            return true
        }
    }
    return false
}

This function works well if your slice is not too large. For longer lists of data, you should consider using a map for storage, which has generally much better lookup performance than iterating over slices.

Go Programming Language Specification does not make any complexity guarantees but in general map lookup should have a complexity of O(1), while finding an element in a slice is O(n).


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

🧑‍🤝‍🧑 Copy a slice in Go

Learn how to make a deep copy of a slice
introduction slice

🖨️ Convert string to []byte or []byte to string in Go

Learn the difference between a string and a byte slice
introduction strings slice

🧠 Print the memory address of a variable in Go

Learn how to find and print the address of a variable or pointer
introduction pointer slice