Slice Containment Check in Go
In Go, finding if an element is present in a slice without iterating over each item can be done efficiently.
Trivial Method
As Mostafa mentioned, a custom method can be created to simplify the task:
func SliceContains(slice []T, target T) bool { for _, item := range slice { if item == target { return true } } return false }
Binary Search
Alternatively, mkb suggested using the binary search from the sort package. This approach requires a pre-sorted slice and is efficient for large datasets.
sort.Slice(slice, func(i, j int) bool { return slice[i] < slice[j] }) idx := sort.Search(len(slice), func(i int) bool { return slice[i] == target }) contains := idx != len(slice) && slice[idx] == target
Map Optimization
If frequent containment checks are required, using a map instead of a slice may provide better performance.
type Set map[string]struct{} func (s Set) Contains(key string) bool { _, ok := s[key] return ok }
Using an empty struct{} value in the map reduces memory overhead and optimizes map performance. Set is commonly used for set-like operations in Go.
The above is the detailed content of How Can I Efficiently Check for Slice Containment in Go?. For more information, please follow other related articles on the PHP Chinese website!