Home > Backend Development > Golang > How Can I Efficiently Check for Value Membership in Go Lists?

How Can I Efficiently Check for Value Membership in Go Lists?

Susan Sarandon
Release: 2024-12-02 01:08:10
Original
956 people have browsed it

How Can I Efficiently Check for Value Membership in Go Lists?

Checking Value Membership in Lists in Go

In Python, the in keyword conveniently checks if a value exists within a list. Similar functionality in Go requires a slightly different approach.

One option is to utilize a map with string keys and integer values. However, this approach requires specifying an unused integer value, which can be inconvenient.

Using a Map with Boolean Values

A more elegant solution involves creating a map with string keys and boolean values. The absence of a key in the map returns the default boolean value of false.

valid := map[string]bool{"red": true, "green": true, "yellow": true, "blue": true}

if valid[x] {
    fmt.Println("found")
} else {
    fmt.Println("not found")
}
Copy after login

Optimizing with a Slice

If you have a large number of valid values, consider using a slice to initialize the map values to true:

for _, v := range []string{"red", "green", "yellow", "blue"} {
    valid[v] = true
}
Copy after login

Shorter Initialization Using Constants

Alternatively, you can create an untyped or boolean constant and optimize the initialization further:

const t = true
valid := map[string]bool{"red": t, "green": t, "yellow": t, "blue": t}
Copy after login

By adopting one of these techniques, you can efficiently check if a value is contained within a list in Go, providing similar functionality to Python's in keyword.

The above is the detailed content of How Can I Efficiently Check for Value Membership in Go Lists?. 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