HowtoGo
Home / Standard Library / The cmp Package
Standard Library

The cmp Package

cmp is a small generics-era package: three functions and one type constraint for ordering and defaulting values, added in Go 1.21.

Examples

Compare returns a three-way result usable directly as a sort comparator. Less is a plain boolean shortcut for the same ordering.

fmt.Println(cmp.Compare(3, 5))
fmt.Println(cmp.Compare(5, 5))
fmt.Println(cmp.Compare(5, 3))

fmt.Println(cmp.Less(3, 5))
fmt.Println(cmp.Less("banana", "apple"))
Output
-1
0
1
true
false
FunctionDescription
Compare[T Ordered](x, y T) int
cmp.Compare(3, 5)
Returns -1 if x < y, 0 if x == y, 1 if x > y
Less[T Ordered](x, y T) bool
cmp.Less(3, 5)
Reports whether x sorts before y
Or[T comparable](vals ...T) T
cmp.Or(0, 0, 7)
Returns the first non-zero-value argument, or the zero value if every argument is zero
Ordered
func Max[T cmp.Ordered](a, b T) T
Type constraint satisfied by any ordered type: integers, floats, and strings
Related: Generics slices Sorting