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

Issue

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: ...

Solution

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
}

Or in Go 1.18 or newer, you can use slices.Contains (from golang.org/x/exp/slices).

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.")
}

Answered By – andybalholm

Answer Checked By – Jay B. (GoLangFix Admin)

Leave a Reply

Your email address will not be published.