cmp
最後更新
cmp 套件(Go 1.21 起)提供比較兩個可排序值的泛型函式,以及代表「可排序型別」的約束 cmp.Ordered。這個套件做什麼
排序、找最大最小、寫二元搜尋時,都需要回答「a 比 b 小、相等,還是大?」。Go 1.21 加入泛型工具後,
cmp 把這個問題標準化:cmp.Compare回傳 -1、0、+1,是slices.SortFunc等函式要求的比較函式格式cmp.Less回傳布林值,適合sort.Slice這類只要「是否小於」的地方cmp.Or回傳第一個非零值的參數,常用來設預設值或組合多個排序條件cmp.Ordered是型別約束,寫泛型函式時表示「這個型別可以用<比較」
和相近工具的差別:內建的
min、max(見 builtin)直接回傳極值;排序與搜尋本身由 slices 負責,cmp 只提供比較的規則。泛型約束的觀念見 型別約束。匯入
- import "cmp"
常用 API
Compare
Compare 比較 x 與 y:x < y 回傳 -1、相等回傳 0、x > y 回傳 +1。字串依位元組順序比較。浮點數的 NaN 被視為比任何數都小,且 NaN 與 NaN 相等,這讓含 NaN 的資料也能穩定排序。簽名:
- func Compare[T Ordered](x, y T) int
範例:
- package main
- import (
- "cmp"
- "fmt"
- "math"
- )
- func main() {
- fmt.Println(cmp.Compare(1, 2))
- fmt.Println(cmp.Compare("b", "a"))
- fmt.Println(cmp.Compare(3.0, 3.0))
- fmt.Println(cmp.Compare(math.NaN(), -100.0))
- }
輸出:
- -1
- 1
- 0
- -1
Compare 搭配 slices.SortFunc
slices.SortFunc 需要一個回傳 int 的比較函式,正好是 cmp.Compare 的格式。依結構體某個欄位排序時,在比較函式中對該欄位呼叫 cmp.Compare;要反向排序就把參數對調。簽名:
- func Compare[T Ordered](x, y T) int
範例:
- package main
- import (
- "cmp"
- "fmt"
- "slices"
- )
- type Product struct {
- Name string
- Price int
- }
- func main() {
- items := []Product{
- {"pen", 30},
- {"book", 250},
- {"cup", 120},
- }
- slices.SortFunc(items, func(a, b Product) int {
- return cmp.Compare(a.Price, b.Price)
- })
- fmt.Println(items)
- slices.SortFunc(items, func(a, b Product) int {
- return cmp.Compare(b.Price, a.Price)
- })
- fmt.Println(items)
- }
輸出:
- [{pen 30} {cup 120} {book 250}]
- [{book 250} {cup 120} {pen 30}]
Less
Less 回傳 x < y 的結果。和直接寫 < 的差別在浮點數:NaN 被視為比所有數字小,與 Compare 的規則一致。用在只需要布林值的場合,例如 sort.Slice。簽名:
- func Less[T Ordered](x, y T) bool
範例:
- package main
- import (
- "cmp"
- "fmt"
- "math"
- "sort"
- )
- func main() {
- fmt.Println(cmp.Less(1, 2))
- fmt.Println(cmp.Less("go", "go"))
- nan := math.NaN()
- fmt.Println(nan < 1.0, cmp.Less(nan, 1.0))
- words := []string{"pear", "fig", "apple"}
- sort.Slice(words, func(i, j int) bool {
- return cmp.Less(words[i], words[j])
- })
- fmt.Println(words)
- }
輸出:
- true
- false
- false true
- [apple fig pear]
Or
Or(Go 1.22 起)回傳參數中第一個不是零值的那個;全部都是零值時回傳零值。兩個常見用途:- 設定預設值:
cmp.Or(userInput, "default") - 多條件排序:先比主要欄位,相等(得到 0)時才比下一個欄位
簽名:
- func Or[T comparable](vals ...T) T
範例:
- package main
- import (
- "cmp"
- "fmt"
- "slices"
- )
- type Student struct {
- Name string
- Grade int
- }
- func main() {
- port := ""
- fmt.Println(cmp.Or(port, "8080"))
- fmt.Println(cmp.Or(0, 0, 5, 9))
- list := []Student{
- {"Ben", 2},
- {"Amy", 1},
- {"Cat", 2},
- {"Abe", 2},
- }
- slices.SortFunc(list, func(a, b Student) int {
- return cmp.Or(
- cmp.Compare(a.Grade, b.Grade),
- cmp.Compare(a.Name, b.Name),
- )
- })
- fmt.Println(list)
- }
輸出:
- 8080
- 5
- [{Amy 1} {Abe 2} {Ben 2} {Cat 2}]
Ordered
Ordered 是型別約束(type constraint),涵蓋所有支援 <、<=、>、>= 的型別:各種整數、浮點數與字串,以及以它們為底層型別的自訂型別(約束中用 ~ 表示)。寫泛型函式時用它限制型別參數。簽名:
- type Ordered interface {
- ~int | ~int8 | ~int16 | ~int32 | ~int64 |
- ~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr |
- ~float32 | ~float64 |
- ~string
- }
範例:
- package main
- import (
- "cmp"
- "fmt"
- )
- type Score int
- func Clamp[T cmp.Ordered](v, lo, hi T) T {
- if v < lo {
- return lo
- }
- if v > hi {
- return hi
- }
- return v
- }
- func main() {
- fmt.Println(Clamp(150, 0, 100))
- fmt.Println(Clamp("m", "a", "k"))
- fmt.Println(Clamp(Score(-5), 0, 10))
- }
輸出:
- 100
- k
- 0
注意:
Ordered 不包含布林、複數、指標與結構體;要排序結構體,請像前面的範例那樣在比較函式中比較個別欄位。重點整理
cmp.Compare回傳 -1/0/+1,直接交給slices.SortFunc使用- 反向排序只要把
Compare的兩個參數對調 cmp.Or取第一個非零值,可用來設預設值與串接多個排序條件Compare與Less把 NaN 視為最小,排序含 NaN 的資料也穩定cmp.Ordered是泛型約束,涵蓋整數、浮點數、字串與其自訂型別