Slices SortFunc Multi Key Sorting
Order structs by several keys with slices.SortFunc and cmp.Compare, flipping the comparison to get descending secondary sorts.
Code
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
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.JSON SorterSort JSON object keys by code point ascending or descending, recursively or top-level only, preserving array order.SemVer SorterParse and sort Semantic Version 2.0.0 strings with prerelease and build metadata, respecting prerelease-below-release precedence.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.
FAQ
- How do you run Slices SortFunc Multi Key Sorting?
- Just run the file; everything it needs ships with the runtime itself.
Report a problem with this exampleOpens a pre-filled issue on GitHub.