实现说明
sort.Interface 与 Reverse 包装可以归结为函数 Len、Less、Swap、main。
使用要点
- 直接运行文件,输出会带上标签,比如
asc:、desc:——输出的每一行都能指回产生它的那次调用。
常见问题
运行「sort.Interface 与 Reverse 包装」会打印什么?
运行文件本身,asc:、desc: 这些前缀各对应一段演示逻辑。
入口签名:func (s ByLatency) Len() int
核心语句
func (s ByLatency) Less(i, j int) bool { return s[i].Latency < s[j].Latency }
func (s ByLatency) Len() int { return len(s) }
func (s ByLatency) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
代码示例
package main
import (
"fmt"
"sort"
)
type Sample struct {
Name string
Latency int
}
// 实现 sort.Interface 三件套:Len、Less、Swap
type ByLatency []Sample
func (s ByLatency) Len() int { return len(s) }
func (s ByLatency) Less(i, j int) bool { return s[i].Latency < s[j].Latency }
func (s ByLatency) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
// 编译期断言:*ByLatency 确实满足 sort.Interface
var _ sort.Interface = (*ByLatency)(nil)
func main() {
samples := []Sample{
{"gateway", 120}, {"auth", 40}, {"billing", 90},
}
// sort.Sort 按接口原地排序,无返回值
sort.Sort(ByLatency(samples))
fmt.Println("asc:", samples)
// sort.Reverse 包一层接口即得降序,无需重写 Less
sort.Sort(sort.Reverse(ByLatency(samples)))
fmt.Println("desc:", samples)
}