Skip to content

Archive

Search

2 articles
Go 10 Sep 2026 6 min read

Search Go Struct Slices with slices.BinarySearchFunc

A slice of structs can be sorted by an ID, timestamp, or other field even though the struct itself has no built-in ordering. When you need repeated lookups in that sorted data, slices.BinarySearchFunc lets the search use the same ordering without building a separate index. The comparator is the part that deserves attention. It doesn’t compare two slice elements. It compares one element from the slice with the search target, and its ordering must agree with the way the slice is sorted.

Go 10 Sep 2026 5 min read

Find Values and Insertion Points with slices.BinarySearch

When a Go slice is already sorted, scanning it from the beginning to find one value throws away useful information. slices.BinarySearch uses that ordering directly. It returns both an index and a found flag, and the index remains useful even when the target isn’t present. That second behavior is easy to overlook. slices.BinarySearch isn’t only a membership check; it also tells you where a missing value belongs if you want to preserve the slice’s sort order.