BinarySearchFunc Finds Struct Records
Project struct records onto a key with slices.BinarySearchFunc: hits return the index, misses return the insertion point for sorted inserts.
Code
package main
import (
"cmp"
"fmt"
"slices"
)
type Account struct {
ID int
Name string
}
func main() {
accounts := []Account{
{ID: 3, Name: "ada"},
{ID: 7, Name: "bob"},
{ID: 12, Name: "cyd"},
}
// BinarySearchFunc:比较器把记录投影成目标键的序,命中返回 true
idx, found := slices.BinarySearchFunc(accounts, 7, func(a Account, target int) int {
return cmp.Compare(a.ID, target)
})
fmt.Println("id 7:", found, idx, accounts[idx].Name)
// 未命中时返回的是插入点,可用于排序插入
missIdx, hit := slices.BinarySearchFunc(accounts, 9, func(a Account, target int) int {
return cmp.Compare(a.ID, target)
})
fmt.Println("id 9:", hit, "insert at", missIdx)
}What the file does
BinarySearchFunc Finds Struct Records comes down to the function main.
What to watch for
- No external packages — everything relies on the language’s built-in APIs.
Using it
Signature: func main()
Running the file prints labeled results such as id 7:, id 9: — each operation’s effect is visible in the output.
Key statements
return cmp.Compare(a.ID, target)
Interactive Tools for This Topic
Binary Text ConverterConvert UTF-8 text to 8-bit binary groups and decode binary back to text with strict validation.Bitwise Operations CalculatorCompute AND, OR, XOR, NOT, and shifts on 32-bit unsigned operands with binary, hex, and signed decimal views.cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.Fuzzy Match TesterTest subsequence fuzzy matching: check whether pattern characters appear in order inside a text, with positions and highlighting.
FAQ
- What does BinarySearchFunc Finds Struct Records print when run?
- Running the file directly is enough — expect labeled output lines such as `id 7:`, `id 9:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.