Sorting a slice in Go is among the issues that you just used to need to re-write each time there was a brand new slice sort. Generally you ended up with the identical code for 2 differing types. Since Go 1.18, and due to the brand new Generics function, that is now not a difficulty. You’ll be able to write a single common kind perform that works for any sort whose values might be ordered.
This text is a part of the Introduction to Go Generics collection. Go right here to see extra.
As an alternative of writing your individual perform, you need to use sorting features
slices.Type()
andslices.SortFunc()
from thegolang.org/x/exp/slices
bundle, launched along with the Go 1.18.
|
|
The one new factor we introduce right here in comparison with our earlier tutorial is the brand new constraints.Ordered
constraint within the sortSlice()
perform. It ensures that the perform can kind values of any sort supporting the operators <
, <=
, >=
, >
. For proof, see the output of the primary()
examples, the place three totally different sort slices are sorted with a single perform:
[0.2 1.2 2.3 51.2]
[a b z]
[0 1 2 3 6]
Sorting is a really pure use case for the brand new Generics function. It makes the code concise and introduces just about no complexity.