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

user1529891 picture user1529891 · Mar 10, 2013 · Viewed 251.9k times · Source

Without iterating over the entire array, how can I check if x in array using Go? Does the language have a construct?

Like Python: if "x" in array: ...

Answer

andybalholm picture andybalholm · Mar 10, 2013

There is no built-in operator to do it in Go. You need to iterate over the array. You can 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.")
}