Cookies management by TermsFeed Cookie Consent

🩰 Sort a slice of any type using Generics in Go

introduction generics generics-intro

Sorting a slice in Go is one of the things that you used to have to re-write every time there was a new slice type. Sometimes you ended up with the same code for two different types. Since Go 1.18, and thanks to the new Generics feature, this is no longer an issue. You can write a single universal sort function that works for any type whose values can be ordered.

This article is part of the Introduction to Go Generics series. Go here to see more.

Instead of writing your own function, you can use sorting functions slices.Sort() and slices.SortFunc() from the golang.org/x/exp/slices package, released together with the Go 1.18.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
package main

import (
    "fmt"
    "sort"

    "golang.org/x/exp/constraints"
)

func sortSlice[T constraints.Ordered](s []T) {
    sort.Slice(s, func(i, j int) bool {
        return s[i] < s[j]
    })
}

func main() {
    floatSlice := []float64{2.3, 1.2, 0.2, 51.2}
    sortSlice(floatSlice)
    fmt.Println(floatSlice)

    stringSlice := []string{"z", "a", "b"}
    sortSlice(stringSlice)
    fmt.Println(stringSlice)

    intSlice := []int{0, 3, 2, 1, 6}
    sortSlice(intSlice)
    fmt.Println(intSlice)
}

The only new thing we introduce here compared to our previous tutorial is the new constraints.Ordered constraint in the sortSlice() function. It guarantees that the function can sort values of any type supporting the operators <, <=, >=, >. For proof, see the output of the main() examples, where three different type slices are sorted with a single function:

[0.2 1.2 2.3 51.2]
[a b z]
[0 1 2 3 6]

Sorting is a very natural use case for the new Generics feature. It makes the code concise and introduces virtually no complexity.


Thank you for being on our site 😊. If you like our tutorials and examples, please consider supporting us with a cup of coffee and we'll turn it into more great Go examples.

Have a great day!

Buy Me A Coffee

🫘 Count the occurrences of an element in a slice in Go

Learn how to count elements in a slice that meet certain conditions
introduction generics generics-intro

🗑️ Remove duplicates from any slice using Generics in Go

Learn how to create a slice with unique values using Generics
introduction slice generics generics-intro

🔉 Reduce function using Generics in Go

Learn how to define a function to accumulate slice values using Generics
introduction generics generics-intro