Searching slices
Searching a slice means finding an element or the first index that matches a condition. Linear search is a range. Binary search needs a sorted slice and sort.Search or slices.BinarySearch.
Detailed Explanation
Most lookups in application code are linear: the slice is small, or it is not sorted. slices.Index(ids, id) and a for loop are the same O(n) idea. Write the loop when the condition is more than equality (user.Active && user.ID == id). Use slices.Index / slices.Contains when you are looking for a value.
Linear search. Walk from 0 to len-1. Return the index or -1. This is the correct algorithm for unsorted data and for "first match" on a predicate that does not define an order. Do not binary-search a list of HTTP handlers.
Binary search. If the slice is sorted by the same key you are asking about, slices.BinarySearch or sort.Search is O(log n). The precondition is easy to violate after an append. If you search more often than you mutate, keep the slice sorted or keep a map.
Maps vs slices. map[ID]User is O(1) average lookup. A slice is O(n) unless sorted and binary-searched. Use a map when identity lookup is the common case. Use a slice when order matters or n is tiny (a handful of options).
sort.Search vs slices.BinarySearch. sort.Search(n, func(i int) bool) returns the first index where the function is true; the function must be a false prefix then a true suffix. slices.BinarySearch(s, v) returns (i, found) for a value. Prefer slices when you have a []T of ordered values.
What it costs. Linear search is predictable and cache-friendly for small n. Binary search on a large []int wins. Binary search on a []string still does O(log n) comparisons, each of which may scan the string. A map of strings may be faster for many lookups. Measure at a few thousand elements if you are unsure.
Code Examples
package main
import (
"fmt"
"slices"
)
func indexOf(ids []int, id int) int {
return slices.Index(ids, id) // -1 if missing
}
func firstActive(users []User) int {
for i, u := range users {
if u.Active {
return i
}
}
return -1
}
type User struct{ Active bool }
func main() {
fmt.Println(indexOf([]int{2, 4, 6}, 4))
}func findSorted(sorted []int, v int) (int, bool) {
return slices.BinarySearch(sorted, v)
}Common Gotchas
`slices.Index` returns -1, not an error
check the result before using it as a slice index.
Binary search on an unsorted slice is silently wrong
sort, or use linear search.
Searching for a pointer's value vs its address are different
`slices.Index` uses `==`.
For repeated lookups, build a map once
`O(n)` preprocess, `O(1)` query.