if-statementgo

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


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