Slices SortFunc Multi Key Sorting

Order structs by several keys with slices.SortFunc and cmp.Compare, flipping the comparison to get descending secondary sorts.

GoData Integrity

Code

gosnippet
34 lines
package main

import (
	"cmp"
	"fmt"
	"slices"
)

type Commit struct {
	Author string
	Files  int
	Day    string
}

func main() {
	commits := []Commit{
		{"ana", 12, "mon"},
		{"bob", 4, "tue"},
		{"ana", 7, "wed"},
		{"cid", 4, "mon"},
	}

	// 多键(multi-key)排序:先按作者,再按文件数降序
	slices.SortFunc(commits, func(a, b Commit) int {
		if c := cmp.Compare(a.Author, b.Author); c != 0 {
			return c
		}
		return cmp.Compare(b.Files, a.Files) // 降序:交换比较方向
	})

	for _, c := range commits {
		fmt.Printf("%s %s files=%d\n", c.Author, c.Day, c.Files)
	}
}

A tour of the code

Slices SortFunc Multi Key Sorting is built around the function main.

A single loop drives the file — for _, c := range commits.

Iteration is driven by for _, c := range commits.

Statements that matter

for _, c := range commits {
	fmt.Printf("%s %s files=%d\n", c.Author, c.Day, c.Files)
}
return cmp.Compare(b.Files, a.Files) // 降序:交换比较方向

Interactive Tools for This Topic

FAQ

How do you run Slices SortFunc Multi Key Sorting?
Just run the file; everything it needs ships with the runtime itself.