Go 中自定义 Pair 类型的排序(按 Key 或 Value)

2次阅读

Go 中自定义 Pair 类型的排序(按 Key 或 Value)

go 中,可通过实现 sort.interface 接口len、swap、less)为自定义结构体(如 pair)提供灵活排序能力,支持按 key 字符串升序、value 整数升序等多种策略,无需依赖第三方库。

go 语言原生 sort 包不直接支持对任意结构体切片排序,但提供了高度可扩展的接口机制:只要类型实现了 sort.Interface(即 Len(), Swap(i,j int), Less(i,j int) bool 三个方法),即可使用 sort.Sort() 进行排序。

以 Pair 结构体为例:

type Pair struct {     Key   string     Value int }

✅ 按 Key 升序排序(字典序)

定义一个类型别名 ByKey 并实现接口:

type ByKey []Pair  func (s ByKey) Len() int           { return len(s) } func (s ByKey) Swap(i, j int)      { s[i], s[j] = s[j], s[i] } func (s ByKey) Less(i, j int) bool { return s[i].Key < s[j].Key }

使用方式:

pairs := []Pair{{"c", 2}, {"a", 1}, {"b", 0}} sort.Sort(ByKey(pairs)) fmt.Println(pairs) // [{a 1} {b 0} {c 2}]

✅ 按 Value 升序排序(数值大小)

同理,定义 ByValue 类型:

type ByValue []Pair  func (s ByValue) Len() int           { return len(s) } func (s ByValue) Swap(i, j int)      { s[i], s[j] = s[j], s[i] } func (s ByValue) Less(i, j int) bool { return s[i].Value < s[j].Value }

调用:

sort.Sort(ByValue(pairs)) fmt.Println(pairs) // [{b 0} {a 1} {c 2}]

? 进阶提示

  • 降序排序? 只需将 Less 中的比较逻辑反转,例如 s[i].Key > s[j].Key;
  • 稳定排序? 使用 sort.Stable() 替代 sort.Sort(),保持相等元素的原始顺序;
  • 一行式简洁写法(Go 1.8+): 可结合 sort.Slice() 直接传入比较函数,无需定义新类型:
// 按 Key 排序(推荐现代写法) sort.Slice(pairs, func(i, j int) bool {     return pairs[i].Key < pairs[j].Key })  // 按 Value 排序 sort.Slice(pairs, func(i, j int) bool {     return pairs[i].Value < pairs[j].Value })

⚠️ 注意:sort.Slice() 是泛型前最简洁的方案,但 sort.Sort() + 自定义类型仍适用于需复用排序逻辑或构建可导出排序器的场景。

综上,Go 的排序机制强调显式与可控——无论是传统接口实现还是现代 sort.Slice 函数式写法,都能精准满足 Pair 级别的多维度排序需求。

text=ZqhQzanResources