Home > Backend Development > Golang > How to Efficiently Check for Membership in Go Slices and Maps?

How to Efficiently Check for Membership in Go Slices and Maps?

Linda Hamilton
Release: 2024-12-13 20:16:15
Original
163 people have browsed it

How to Efficiently Check for Membership in Go Slices and Maps?

Effective "if x in" Syntax in Go: Comparison to Python's Construct

Go does not natively provide an "if x in" construct similar to Python. However, there are effective techniques to achieve the same functionality for arrays or slices, and by using maps for more efficient membership checks.

For Arrays and Slices

In Go 1.18 and later, slices offer the Contains function to conveniently check for membership:

if contains.Contains(array, "x") {
  // Perform actions
}
Copy after login

Prior to Go 1.18, there was no built-in operator for array or slice membership checks. A custom function could be implemented:

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

For Maps

Maps provide more efficient membership checks by storing key-value pairs. To check if an element exists in a map, use the following syntax:

if visitedURL[thisSite] {
    // Perform actions
}
Copy after login

Where visitedURL is a map with keys representing elements and values representing their presence (e.g., true for existing elements).

The above is the detailed content of How to Efficiently Check for Membership in Go Slices and Maps?. 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