cmp

Guided tour · Collections · pkg.go.dev →

Generic comparison helpers (Go 1.21+). The glue between the old world and slices.SortFunc / maps / binary search.

Compare and Less

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

Less — the boolean version

cmp.Less(1.0, 2.0)  // true

Or — fall through to the next comparison

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),
    )
})

Or for zero-value fallback (any type)

cmp.Or on non-comparable-semantics returns the first non-zero value — a generic COALESCE.

name := cmp.Or(userInput, envVar, "default")