cmp.Compare and cmp.Less
func Compare[T Ordered](x, y T) int
func Less[T Ordered](x, y T) bool
type Ordered interface {
~int | ~int8 | ~int16 | ~int32 | ~int64 |
~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr |
~float32 | ~float64 |
~string
}Compare returns -1, 0, or +1. For floats, NaN equals NaN and is less than every non-NaN; -0.0 equals 0.0.
| Parameter | Description |
|---|---|
x, y | Values of an Ordered type: signed and unsigned integers, floats, or strings, including named types whose underlying type is one of those. |
Returns: Compare returns an int in {-1, 0, +1}. Less returns whether x is less than y under the same rules.
- math.NaN() compared with 0.0 yields -1; 0.0 compared with NaN yields +1; two NaNs yield 0. math.Copysign(0, -1) compared with 0.0 yields 0.
package main
import (
"cmp"
"fmt"
"math"
)
func main() {
fmt.Println(cmp.Compare(1, 2), cmp.Compare(2, 2), cmp.Compare(3, 2))
fmt.Println(cmp.Less(1, 2), cmp.Less(2, 1), cmp.Less(2, 2))
nan := math.NaN()
fmt.Println(cmp.Compare(nan, 0.0), cmp.Compare(0.0, nan), cmp.Compare(nan, nan))
fmt.Println(cmp.Compare(math.Copysign(0, -1), 0.0))
}Expected output
-1 0 1
true false false
-1 1 0
0
Related: slices.Sort, sort, Official cmp.Compare