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
| Name | Type | Description |
|---|---|---|
| x | S | Input value or collection to process. |
| target | T | Value to find in the ordered collection. |
| cmp | func(E, T) int | Comparison 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)}