Checking Element Presence in Go Slices
In Go, a slice doesn't natively include a method like slice.contains(object) for determining the presence of an element. Instead, a common solution is to iterate through each element to conduct the search.
Alternative Approaches:
Custom Method:
Creating a custom slice.contains() method is a straightforward option, as indicated by Mostafa.
package main import "fmt" func main() { slice := []int{1, 2, 3} if sliceContains(slice, 2) { fmt.Println("Contains") } else { fmt.Println("Not contains") } } func sliceContains(slice []int, object int) bool { for _, v := range slice { if v == object { return true } } return false }
Binary Search:
As suggested by mkb, utilizing the sort package's binary search algorithm offers a more efficient approach for large slices.
package main import ( "fmt" "sort" ) func main() { slice := []int{1, 2, 3} sort.Ints(slice) index := sort.SearchInts(slice, 2) if index != len(slice) { fmt.Println("Contains") } else { fmt.Println("Not contains") } }
Using a Map:
If numerous existence checks are anticipated, using a map as an alternative to a slice provides a more efficient solution.
package main import ( "fmt" "sync" ) func main() { slice := []int{1, 2, 3} m := make(map[int]struct{}, len(slice)) for _, v := range slice { m[v] = struct{}{} } if _, exists := m[2]; exists { fmt.Println("Contains") } else { fmt.Println("Not contains") } }
In this scenario, a map[string]struct{} is frequently employed for sets due to its optimized internal map type for such values.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3