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 只提供比較的規則。泛型約束的觀念見 型別約束。

匯入


  1. import "cmp"

常用 API


Compare


Compare 比較 x 與 y:x < y 回傳 -1、相等回傳 0、x > y 回傳 +1。字串依位元組順序比較。浮點數的 NaN 被視為比任何數都小,且 NaN 與 NaN 相等,這讓含 NaN 的資料也能穩定排序。
簽名:
  1. func Compare[T Ordered](x, y T) int

範例:
  1. package main
  2. import (
  3. "cmp"
  4. "fmt"
  5. "math"
  6. )
  7. func main() {
  8. fmt.Println(cmp.Compare(1, 2))
  9. fmt.Println(cmp.Compare("b", "a"))
  10. fmt.Println(cmp.Compare(3.0, 3.0))
  11. fmt.Println(cmp.Compare(math.NaN(), -100.0))
  12. }

輸出:
  1. -1
  2. 1
  3. 0
  4. -1

Compare 搭配 slices.SortFunc


slices.SortFunc 需要一個回傳 int 的比較函式,正好是 cmp.Compare 的格式。依結構體某個欄位排序時,在比較函式中對該欄位呼叫 cmp.Compare;要反向排序就把參數對調。
簽名:
  1. func Compare[T Ordered](x, y T) int

範例:
  1. package main
  2. import (
  3. "cmp"
  4. "fmt"
  5. "slices"
  6. )
  7. type Product struct {
  8. Name string
  9. Price int
  10. }
  11. func main() {
  12. items := []Product{
  13. {"pen", 30},
  14. {"book", 250},
  15. {"cup", 120},
  16. }
  17. slices.SortFunc(items, func(a, b Product) int {
  18. return cmp.Compare(a.Price, b.Price)
  19. })
  20. fmt.Println(items)
  21. slices.SortFunc(items, func(a, b Product) int {
  22. return cmp.Compare(b.Price, a.Price)
  23. })
  24. fmt.Println(items)
  25. }

輸出:
  1. [{pen 30} {cup 120} {book 250}]
  2. [{book 250} {cup 120} {pen 30}]

Less


Less 回傳 x < y 的結果。和直接寫 < 的差別在浮點數:NaN 被視為比所有數字小,與 Compare 的規則一致。用在只需要布林值的場合,例如 sort.Slice。
簽名:
  1. func Less[T Ordered](x, y T) bool

範例:
  1. package main
  2. import (
  3. "cmp"
  4. "fmt"
  5. "math"
  6. "sort"
  7. )
  8. func main() {
  9. fmt.Println(cmp.Less(1, 2))
  10. fmt.Println(cmp.Less("go", "go"))
  11. nan := math.NaN()
  12. fmt.Println(nan < 1.0, cmp.Less(nan, 1.0))
  13. words := []string{"pear", "fig", "apple"}
  14. sort.Slice(words, func(i, j int) bool {
  15. return cmp.Less(words[i], words[j])
  16. })
  17. fmt.Println(words)
  18. }

輸出:
  1. true
  2. false
  3. false true
  4. [apple fig pear]

Or


Or(Go 1.22 起)回傳參數中第一個不是零值的那個;全部都是零值時回傳零值。兩個常見用途:
  • 設定預設值:cmp.Or(userInput, "default")
  • 多條件排序:先比主要欄位,相等(得到 0)時才比下一個欄位

簽名:
  1. func Or[T comparable](vals ...T) T

範例:
  1. package main
  2. import (
  3. "cmp"
  4. "fmt"
  5. "slices"
  6. )
  7. type Student struct {
  8. Name string
  9. Grade int
  10. }
  11. func main() {
  12. port := ""
  13. fmt.Println(cmp.Or(port, "8080"))
  14. fmt.Println(cmp.Or(0, 0, 5, 9))
  15. list := []Student{
  16. {"Ben", 2},
  17. {"Amy", 1},
  18. {"Cat", 2},
  19. {"Abe", 2},
  20. }
  21. slices.SortFunc(list, func(a, b Student) int {
  22. return cmp.Or(
  23. cmp.Compare(a.Grade, b.Grade),
  24. cmp.Compare(a.Name, b.Name),
  25. )
  26. })
  27. fmt.Println(list)
  28. }

輸出:
  1. 8080
  2. 5
  3. [{Amy 1} {Abe 2} {Ben 2} {Cat 2}]

Ordered


Ordered 是型別約束(type constraint),涵蓋所有支援 <、<=、>、>= 的型別:各種整數、浮點數與字串,以及以它們為底層型別的自訂型別(約束中用 ~ 表示)。寫泛型函式時用它限制型別參數。
簽名:
  1. type Ordered interface {
  2. ~int | ~int8 | ~int16 | ~int32 | ~int64 |
  3. ~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr |
  4. ~float32 | ~float64 |
  5. ~string
  6. }

範例:
  1. package main
  2. import (
  3. "cmp"
  4. "fmt"
  5. )
  6. type Score int
  7. func Clamp[T cmp.Ordered](v, lo, hi T) T {
  8. if v < lo {
  9. return lo
  10. }
  11. if v > hi {
  12. return hi
  13. }
  14. return v
  15. }
  16. func main() {
  17. fmt.Println(Clamp(150, 0, 100))
  18. fmt.Println(Clamp("m", "a", "k"))
  19. fmt.Println(Clamp(Score(-5), 0, 10))
  20. }

輸出:
  1. 100
  2. k
  3. 0

注意:Ordered 不包含布林、複數、指標與結構體;要排序結構體,請像前面的範例那樣在比較函式中比較個別欄位。

重點整理


  • cmp.Compare 回傳 -1/0/+1,直接交給 slices.SortFunc 使用
  • 反向排序只要把 Compare 的兩個參數對調
  • cmp.Or 取第一個非零值,可用來設預設值與串接多個排序條件
  • Compare 與 Less 把 NaN 視為最小,排序含 NaN 的資料也穩定
  • cmp.Ordered 是泛型約束,涵蓋整數、浮點數、字串與其自訂型別

資料來源