Standard library / slices
slices.BinarySearch()
Searches an ascending sorted slice; returns the earliest matching index or the insertion index and false. Expected stdout: '1 true\n'.
Formal Syntax & Structure
go syntaxgo
func BinarySearch[S ~[]E, E cmp.Ordered](x S, target E) (int, bool)Parameters & Attributes
| Name | Type | Description |
|---|---|---|
| x | S | Input value or collection to process. |
| target | E | Value to find in the ordered collection. |
Return Value
(int, bool)
Index and whether an equal value was found.
Working Example
Example Snippetgo
package main
import ( "fmt" "slices")
func main() { i, ok := slices.BinarySearch([]int{1, 3, 3, 7}, 3) fmt.Println(i, ok)}