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.

GoData Integrity

Code

gosnippet
35 lines
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

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.