package cmp
import "cmp"
Package cmp 提供与比较有序值相关的类型和函数。
Index
Examples
Functions
func Compare
func Compare[T Ordered](x, y T) int
Compare 返回
如果 x 小于 y,则为 -1, 如果 x 等于 y,则为 0, 如果 x 大于 y,则为 +1。
对于浮点类型,NaN 被认为小于任何非 NaN,
NaN 被认为等于 NaN,并且 -0.0 等于 0.0。
Output:Example
package main
import (
"cmp"
"fmt"
"math"
)
func main() {
fmt.Println(cmp.Compare(1, 2))
fmt.Println(cmp.Compare("a", "aa"))
fmt.Println(cmp.Compare(1.5, 1.5))
fmt.Println(cmp.Compare(math.NaN(), 1.0))
}
-1
-1
0
-1
func Less
func Less[T Ordered](x, y T) bool
Less 报告 x 是否小于 y。
对于浮点类型,NaN 被认为小于任何非 NaN,
并且 -0.0 不小于(等于)0.0。
Output:Example
package main
import (
"cmp"
"fmt"
"math"
)
func main() {
fmt.Println(cmp.Less(1, 2))
fmt.Println(cmp.Less("a", "aa"))
fmt.Println(cmp.Less(1.0, math.NaN()))
fmt.Println(cmp.Less(math.NaN(), 1.0))
}
true
true
false
true
func Or
func Or[T comparable](vals ...T) T
Or 返回其参数中第一个不等于零值的参数。
如果没有任何参数非零,则返回零值。
Output: Output:Example
package main
import (
"cmp"
"fmt"
)
func main() {
// Suppose we have some user input
// that may or may not be an empty string
userInput1 := ""
userInput2 := "some text"
fmt.Println(cmp.Or(userInput1, "default"))
fmt.Println(cmp.Or(userInput2, "default"))
fmt.Println(cmp.Or(userInput1, userInput2, "default"))
}
default
some text
some text
Example (Sort)
package main
import (
"cmp"
"fmt"
"slices"
"strings"
)
func main() {
type Order struct {
Product string
Customer string
Price float64
}
orders := []Order{
{"foo", "alice", 1.00},
{"bar", "bob", 3.00},
{"baz", "carol", 4.00},
{"foo", "alice", 2.00},
{"bar", "carol", 1.00},
{"foo", "bob", 4.00},
}
// Sort by customer first, product second, and last by higher price
slices.SortFunc(orders, func(a, b Order) int {
return cmp.Or(
strings.Compare(a.Customer, b.Customer),
strings.Compare(a.Product, b.Product),
cmp.Compare(b.Price, a.Price),
)
})
for _, order := range orders {
fmt.Printf("%s %s %.2f\n", order.Product, order.Customer, order.Price)
}
}
foo alice 2.00
foo alice 1.00
bar bob 3.00
foo bob 4.00
bar carol 1.00
baz carol 4.00
Types
type Ordered
type Ordered interface { ~int | ~int8 | ~int16 | ~int32 | ~int64 | ~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr | ~float32 | ~float64 | ~string }
Ordered 是一个约束,允许任何有序类型:任何 支持 < <= >= > 运算符的类型。 如果未来 Go 版本添加了新的有序类型, 该约束将被修改以包含它们。
注意,浮点类型可能包含 NaN("非数字")值。 当将 NaN 值与任何其他值(无论是否为 NaN)比较时, == 或 < 等运算符将始终报告 false。 有关比较 NaN 值的一致方法,请参见 Compare 函数。