Slices Sort Generic Ordering
Order slices of any comparable type with the generics-based slices package — sort, sorted, and custom comparisons without interface boilerplate.
Code
package main
import (
"fmt"
"slices"
)
func main() {
nums := []int{42, 7, 19, 3}
slices.Sort(nums)
fmt.Println("sorted:", nums)
words := []string{"pear", "apple", "fig"}
ordered := slices.Sorted(slices.Strings)
fmt.Println("sorted strings:", ordered)
type item struct {
name string
score int
}
players := []item{{"ada", 9}, {"bob", 7}, {"cy", 9}}
slices.SortFunc(players, func(a, b item) int {
if a.score != b.score {
return b.score - a.score
}
return a.name < b.name // 平分时按名字
})
for _, p := range players {
fmt.Printf("%s=%d\n", p.name, p.score)
}
}Inside the snippet
Slices Sort Generic Ordering is built around the function main.
Repetition is confined to for _, p := range players — the rest of the file is straight-line.
Using it
The demo output is labeled (sorted:, sorted strings:), so the printed lines read as a trace of the operations that ran.
Key statements
for _, p := range players {
fmt.Printf("%s=%d\n", p.name, p.score)
}
return a.name < b.name // 平分时按名字
return b.score - a.score
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.
FAQ
- What does Slices Sort Generic Ordering print when run?
- Run it as a complete program — the output lines carry labels such as `sorted:`, `sorted strings:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.