cmp.Compare — the -1/0/+1 function
Used with slices.SortFunc, slices.BinarySearchFunc, and similar. Handles NaN sensibly.
cmp.Compare(1, 2) // -1
cmp.Compare(2, 2) // 0
cmp.Compare(3, 2) // +1
cmpGeneric comparison helpers (Go 1.21+). The glue between the old world and slices.SortFunc / maps / binary search.
Used with slices.SortFunc, slices.BinarySearchFunc, and similar. Handles NaN sensibly.
cmp.Compare(1, 2) // -1
cmp.Compare(2, 2) // 0
cmp.Compare(3, 2) // +1
cmp.Less(1.0, 2.0) // true
Build multi-key comparators: first compare field A, if equal, compare field B.
type P struct{ Last, First string; Age int }
slices.SortFunc(people, func(a, b P) int {
return cmp.Or(
cmp.Compare(a.Last, b.Last),
cmp.Compare(a.First, b.First),
cmp.Compare(a.Age, b.Age),
)
})
cmp.Or on non-comparable-semantics returns the first non-zero value — a generic COALESCE.
name := cmp.Or(userInput, envVar, "default")