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 }
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 }
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 }
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!