Checking List Membership in Go: An Alternative to the Python "in" Keyword
In Python, the "in" keyword provides a convenient way to check if a value exists within a list. Go, however, does not offer a direct equivalent.
Approximating the "in" Keyword with a Map
One approach in Go is to leverage a map[string]bool as a representation of a set. By storing valid values as keys and assigning true values, you can test for membership by checking if a key is present in the map:
valid := map[string]bool{"red": true, "green": true, "yellow": true, "blue": true} if valid[x] { fmt.Println("found") } else { fmt.Println("not found") }
Utilizing Zero Values
Take advantage of the fact that when a key is not found in a map, the zero value for bool (false) is returned. This allows you to omit the explicit assignment of true values, simplifying the initialization:
valid := map[string]bool{"red", "green", "yellow", "blue"} if valid[x] { fmt.Println("found") } else { fmt.Println("not found") }
Optimizations
For scenarios with a large number of valid values, consider using a for range loop to initialize the map. This provides a compact solution:
for _, v := range []string{"red", "green", "yellow", "blue"} { valid[v] = true }
Additionally, you can optimize the code by defining a const variable to avoid repetitive boolean values:
const t = true valid := map[string]bool{"red": t, "green": t, "yellow": t, "blue": t}
The above is the detailed content of How Can I Efficiently Check List Membership in Go?. For more information, please follow other related articles on the PHP Chinese website!