HiveBrain v1.2.0
Get Started
← Back to all entries
patterngoCritical

Does Go have "if x in" construct similar to Python?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
havesimilarconstructdoespython

Problem

How can I check if x is in an array without iterating over the entire array, using Go? Does the language have a construct for this?

Like in Python:
if "x" in array:
# do something

Solution

Since Go 1.18 or newer, you can use slices.Contains.

Before Go 1.18 there was no built-in operator. You needed to iterate over the array. You had to write your own function to do it, like this:

func stringInSlice(a string, list []string) bool {
    for _, b := range list {
        if b == a {
            return true
        }
    }
    return false
}


If you want to be able to check for membership without iterating over the whole list, you need to use a map instead of an array or slice, like this:

visitedURL := map[string]bool {
    "http://www.google.com": true,
    "https://paypal.com": true,
}
if visitedURL[thisSite] {
    fmt.Println("Already been here.")
}

Code Snippets

func stringInSlice(a string, list []string) bool {
    for _, b := range list {
        if b == a {
            return true
        }
    }
    return false
}
visitedURL := map[string]bool {
    "http://www.google.com": true,
    "https://paypal.com": true,
}
if visitedURL[thisSite] {
    fmt.Println("Already been here.")
}

Context

Stack Overflow Q#15323767, score: 565

Revisions (0)

No revisions yet.