How to Use the cmp Package for Comparison Functions
Use cmp.Compare to compare two values of the same type, returning -1, 0, or 1 to indicate less than, equal, or greater than. This function replaces manual comparison logic for any comparable type.
package main
import (
"fmt"
"cmp"
)
func main() {
a := []int{1, 2, 3}
b := []int{1, 2, 4}
result := cmp.Compare(a, b)
fmt.Println(result) // result is -1 because a < b
}
For sorting slices, use cmp.Ordered with slices.SortFunc or slices.BinarySearchFunc.
package main
import (
"fmt"
"cmp"
"slices"
)
func main() {
items := []string{"b", "a", "c"}
slices.SortFunc(items, cmp.Compare[string])
fmt.Println(items) // items is now ["a", "b", "c"]
}
For custom comparison logic, pass a function to slices.SortFunc.
package main
import (
"fmt"
"cmp"
"slices"
)
func main() {
items := []string{"apple", "pear", "kiwi", "banana"}
slices.SortFunc(items, func(a, b string) int {
return cmp.Compare(len(a), len(b))
})
fmt.Println(items) // Sorted by length: ["pear", "kiwi", "apple", "banana"]
}
The cmp package also provides Less, Greater, Equal, and Max/Min functions for specific use cases.
package main
import (
"fmt"
"cmp"
)
func main() {
a := 10
b := 20
if cmp.Less(a, b) {
fmt.Println("a is less than b")
}
maxVal := cmp.Max(a, b)
fmt.Println(maxVal) // Output: 20
}
For comparing values of different types, use type assertions or explicit conversions before calling cmp.Compare.