Home >Backend Development >Golang >Does Go Have an Equivalent to Python's 'if x in' for Array Membership?

Does Go Have an Equivalent to Python's 'if x in' for Array Membership?

Susan Sarandon
Susan SarandonOriginal
2024-12-27 01:04:09147browse

Does Go Have an Equivalent to Python's

How to Find Array Elements Like Python's "if x in" Construct in Go

In Python, you can easily check if an element exists in an array using the "if x in" construct. Does Go offer a similar mechanism for checking array membership without iterating through the entire array?

Answer

Go does not have a direct equivalent of Python's "if x in" construct for arrays. However, starting with Go 1.18, you can use the slices.Contains function for slices to achieve a similar result:

if slices.Contains(array, x) {
    // do something
}

Pre-Go 1.18 Solution

Prior to Go 1.18, there was no built-in operator for checking array membership. You had to iterate over the array and use a custom function like the following:

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

Alternative Approach: Maps

To avoid the need for iteration, you can utilize a map instead of an array or slice:

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

The above is the detailed content of Does Go Have an Equivalent to Python's 'if x in' for Array Membership?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn