Standard library / slices

slices.BinarySearchFunc()

Searches a slice sorted consistently with the element-to-target comparator. Returns the earliest match or insertion point. Expected stdout: '1 true\n'.

Formal Syntax & Structure

go syntaxgo
func BinarySearchFunc[S ~[]E, E, T any](x S, target T, cmp func(E, T) int) (int, bool)

Parameters & Attributes

NameTypeDescription
xSInput value or collection to process.
targetTValue to find in the ordered collection.
cmpfunc(E, T) intComparison callback; negative, zero, or positive for less, equivalent, or greater.

Return Value

(int, bool)

Searches a slice sorted consistently with the element-to-target comparator. Returns the earliest match or insertion point.

Working Example

Example Snippetgo
package main
import (  "cmp"  "fmt"  "slices")
func main() {  i, ok := slices.BinarySearchFunc([]string{"a", "bb", "ccc"}, 2, func(s string, n int) int { return cmp.Compare(len(s), n) })  fmt.Println(i, ok)}
Go Reference