Go 1.27 reference · Slices, Maps, Iterators and JSON
Go slices.Contains, Index and BinarySearch Function
Search slices: check membership, find an index, or binary-search a sorted slice.
Go 1.27 Since 1.21
Syntax
func Contains[S ~[]E, E comparable](s S, v E) bool func Index(s S, v E) int func BinarySearch(x S, target E) (int, bool)
Parameters
| Parameter | Description |
|---|---|
Contains / Index |
Linear search. |
IndexFunc / ContainsFunc |
With a predicate. |
BinarySearch |
Sorted slices: position and found. |
Examples
package main
import (
"fmt"
"slices"
)
func main() {
roles := []string{"viewer", "editor"}
fmt.Println(slices.Contains(roles, "editor"), slices.Index(roles, "admin"))
i := slices.IndexFunc([]int{3, 8, 12}, func(n int) bool { return n > 5 })
fmt.Println(i)
}
Output
true -1 1
Run this on your computer — see “Get Started” for setup.
package main
import (
"fmt"
"slices"
)
func main() {
sorted := []int{10, 20, 30, 40}
pos, found := slices.BinarySearch(sorted, 30)
fmt.Println(pos, found)
pos, found = slices.BinarySearch(sorted, 25)
fmt.Println(pos, found, slices.Insert(sorted, pos, 25))
}
Output
2 true 2 false [10 20 25 30 40]
Run this on your computer — see “Get Started” for setup.
Version history
| Version | Change |
|---|---|
| Go 1.21 | Added |
Related
slices.Sort and slices.SortFunc· Sort a slice in place in ascending order, or with a comparison function for custom and multi-key ordering.- Go Arrays and Slices · tutorial