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

Create a free account to save this page, take notes and track your progress. Sign in

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

ParameterDescription
Contains / Index Linear search.
IndexFunc / ContainsFunc With a predicate.
BinarySearch Sorted slices: position and found.

Examples

Example 1
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.

Binary search and insert
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

VersionChange
Go 1.21Added

Was this page helpful?