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
Release: 2024-12-27 01:04:09
Original
141 people have browsed it

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
}
Copy after login

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
}
Copy after login

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

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template