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