Skip to main content
Sometimes you’ll want to sort a collection by something other than its natural order. For example, sorting strings by their length instead of alphabetically.

Custom String Sorting

Implement a comparison function for custom sorting. cmp.Compare is helpful for this:
fruits := []string{"peach", "banana", "kiwi"}

// Comparison function for string lengths
lenCmp := func(a, b string) int {
    return cmp.Compare(len(a), len(b))
}

// Sort using custom comparison
slices.SortFunc(fruits, lenCmp)
fmt.Println(fruits)
// Output: [kiwi peach banana]

Sorting Custom Types

Use the same technique to sort slices of values that aren’t built-in types:
type Person struct {
    name string
    age  int
}

people := []Person{
    Person{name: "Jax", age: 37},
    Person{name: "TJ", age: 25},
    Person{name: "Alex", age: 72},
}

// Sort people by age
slices.SortFunc(people,
    func(a, b Person) int {
        return cmp.Compare(a.age, b.age)
    })
fmt.Println(people)
// Output: [{TJ 25} {Jax 37} {Alex 72}]
If the struct is large, consider using *Person instead and adjust the sorting function accordingly. If in doubt, benchmark!

Key Functions

slices.SortFunc
func[S ~[]E, E any](x S, cmp func(a, b E) int)
Sorts a slice using a custom comparison function
cmp.Compare
func[T Ordered](x, y T) int
Returns -1 if x < y, 0 if x == y, +1 if x > y

Package Reference

Build docs developers (and LLMs) love