Compare ordered values with cmp
Compare ordered values with cmp
cmp.Compare returns -1, 0 or 1 for less, equal or greater according to its ordering. It works with ordered types such as integers, floats and strings. cmp.Less returns a Boolean. These generic helpers were introduced in Go 1.21; cmp.Or was added in Go 1.22.
package main
import ( "cmp" "fmt")
func main() { fmt.Println(cmp.Compare(3, 8), cmp.Compare(8, 8), cmp.Compare(9, 8)) fmt.Println(cmp.Less("a", "b")) fmt.Println(cmp.Or("", "default"))}Unlike subtracting two integers, Compare does not risk subtraction overflow. Or returns the first nonzero argument, or the zero value if all are zero; it is not lazy evaluation. All argument expressions are evaluated before the call. Do not use it if zero is a legitimate explicit setting rather than absence.
Expected output:
-1 0 1truedefaultHandle NaN consistently
package main
import ( "cmp" "fmt" "math")
func main() { nan := math.NaN() fmt.Println(nan < 1, cmp.Less(nan, 1)) fmt.Println(cmp.Compare(nan, nan), cmp.Compare(1.0, nan)) fmt.Println(cmp.Compare(math.Copysign(0, -1), 0.0))}cmp orders NaN before non-NaN values, considers NaNs equal to each other for ordering, and treats negative and positive zero as equal. This differs from ordinary floating-point comparisons. It helps construct consistent sorting comparators; it does not change the language behavior of == or <.
Expected output:
false true0 10Try it locally
Compare two strings "beta" and "alpha" using cmp.Compare; choose a nonempty label from "" and "guest" with cmp.Or.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Core library 03: Compare ordered values with cmp
Check the lesson objective before moving on.
How does cmp.Compare(math.NaN(),math.NaN()) behave?
Does cmp.Or evaluate its argument expressions lazily?