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.

GoData Integrity

Code

gosnippet
32 lines
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

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:`.