patterngoCritical
Does Go have "if x in" construct similar to Python?
Viewed 0 times
havesimilarconstructdoespython
Problem
How can I check if
Like in Python:
x is in an array without iterating over the entire array, using Go? Does the language have a construct for this?Like in Python:
if "x" in array:
# do something
Solution
Since Go 1.18 or newer, you can use
Before Go 1.18 there was no built-in operator. You needed to iterate over the array. You had to write your own function to do it, like this:
If you want to be able to check for membership without iterating over the whole list, you need to use a map instead of an array or slice, like this:
slices.Contains.Before Go 1.18 there was no built-in operator. You needed to iterate over the array. You had to write your own function to do it, like this:
func stringInSlice(a string, list []string) bool {
for _, b := range list {
if b == a {
return true
}
}
return false
}If you want to be able to check for membership without iterating over the whole list, you need to use a map instead of an array or slice, like this:
visitedURL := map[string]bool {
"http://www.google.com": true,
"https://paypal.com": true,
}
if visitedURL[thisSite] {
fmt.Println("Already been here.")
}Code Snippets
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.")
}Context
Stack Overflow Q#15323767, score: 565
Revisions (0)
No revisions yet.