Home >Backend Development >Golang >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") }
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 }
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}
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!