Go: Find an element in a slice
Go has no generic search function for slices or arrays. It's straightforward to write your own linear search.
// Contains tells whether a contains x.
func Contains(a []string, x string) bool {
for _, n := range a {
if x == n {
return true
}
}
return false
}
// Find returns the smallest index i at which x == a[i],
// or len(a) if there is no such index.
func Find(a []string, x string) int {
for i, n := range a {
if x == n {
return i
}
}
return len(a)
}
More efficient alternatives
If the slice is sorted, the search can be performed more efficiently with a binary search.
If you are doing many searches, consider using a map instead.
Comments
Be the first to comment!