Sort Interface With The Reverse Wrapper
Give a slice Len, Less, and Swap methods to satisfy sort.Interface, then wrap it in sort.Reverse for descending order without rewriting the comparator.
Code
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)
}What the code does
The snippet is organized around the functions Len, Less, Swap and main.
Applying it
Entry signature: func (s ByLatency) Len() int
The demo output is labeled (asc:, desc:), so every line in the printed output names the step that produced it.
Statements that matter
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] }
Interactive Tools for This Topic
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.Line SorterSort text lines ascending or descending with numeric-aware ordering, duplicate removal, empty-line filtering, and locale-aware comparison.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.Text ReverserReverse text by characters, words, or lines, counting Unicode code points so emoji stay intact.
FAQ
- What does Sort Interface With The Reverse Wrapper print when run?
- No setup needed: run the file and look for labeled lines like `asc:`, `desc:` in the output.
Report a problem with this exampleOpens a pre-filled issue on GitHub.