go – Contains method for a slice
go – Contains method for a slice
Mostafa has already pointed out that such a method is trivial to write, and mkb gave you a hint to use the binary search from the sort package. But if you are going to do a lot of such contains checks, you might also consider using a map instead.
Its trivial to check if a specific map key exists by using the value, ok := yourmap[key]
idiom. Since you arent interested in the value, you might also create a map[string]struct{}
for example. Using an empty struct{}
here has the advantage that it doesnt require any additional space and Gos internal map type is optimized for that kind of values. Therefore, map[string] struct{}
is a popular choice for sets in the Go world.
No, such method does not exist, but is trivial to write:
func contains(s []int, e int) bool {
for _, a := range s {
if a == e {
return true
}
}
return false
}
You can use a map if that lookup is an important part of your code, but maps have cost too.
go – Contains method for a slice
The sort package provides the building blocks if your slice is sorted or you are willing to sort it.
input := []string{bird, apple, ocean, fork, anchor}
sort.Strings(input)
fmt.Println(contains(input, apple)) // true
fmt.Println(contains(input, grow)) // false
...
func contains(s []string, searchterm string) bool {
i := sort.SearchStrings(s, searchterm)
return i < len(s) && s[i] == searchterm
}
SearchString
promises to return the index to insert x if x is not present (it could be len(a))
, so a check of that reveals whether the string is contained the sorted slice.