Home >Backend Development >Golang >How to Efficiently Check for Element Membership in Go Arrays?
Checking Membership in Arrays in Go
In Go, unlike Python, there is no built-in construct equivalent to Python's "if x in" for checking the presence of an element in an array.
Post Go 1.18 (Recommended Approach)
Starting with Go 1.18, you can use the slices.Contains function to efficiently check for membership in a slice.
if slices.Contains(array, "x") { // Do something }
Pre Go 1.18 (Alternative Methods)
If you're using an older version of Go, you have two options:
func stringInSlice(a string, list []string) bool { for _, b := range list { if b == a { return true } } return false }
visitedURL := map[string]bool{ "http://www.google.com": true, "https://paypal.com": true, } if visitedURL["thisSite"] { fmt.Println("Already been here.") }
Remember to choose the appropriate approach based on the size and nature of your data collection.
The above is the detailed content of How to Efficiently Check for Element Membership in Go Arrays?. For more information, please follow other related articles on the PHP Chinese website!