Is there anything similar to a slice.contains(object)
method in Go without having to do a search through each element in a slice?
相关问题
- Golang mongodb aggregation
- How to flatten out a nested json structure in go
- how to install private repo using glide golang
- How to convert a string to a byte array which is c
- IntelliJ 2017.1.2 GOLANG debug does not work on br
相关文章
- Can I run a single test in a suite?
- How to check if a request was cancelled
- Is it possible to implement an interface with unex
- How to access value of first index of array in Go
- Embedded Interface
- Why does slice [:-0] return empty list in Python
- Python negative zero slicing
- How to represent an array with mixed types
Instead of using a
slice
,map
may be a better solution.simple example:
http://play.golang.org/p/CEG6cu4JTf
Not sure generics are needed here. You just need a contract for your desired behavior. Doing the following is no more than what you would have to do in other languages if you wanted your own objects to behave themselves in collections, by overriding Equals() and GetHashCode() for instance.
You can use the reflect package to iterate over an interface whose concrete type is a slice:
https://play.golang.org/p/jL5UD7yCNq
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.
It's trivial to check if a specific map key exists by using the
value, ok := yourmap[key]
idiom. Since you aren't interested in the value, you might also create amap[string]struct{}
for example. Using an emptystruct{}
here has the advantage that it doesn't require any additional space and Go's internal map type is optimized for that kind of values. Therefore,map[string] struct{}
is a popular choice for sets in the Go world.If the slice is sorted, there is a binary search implemented in the
sort
package.