Slices Sort Generic Ordering

Order slices of any comparable type with the generics-based slices package — sort, sorted, and custom comparisons without interface boilerplate.

GoData Integrity

Code

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

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:`.