How to sort []int32


(AkezhanOb1) #1

How to sort slice of 32bit integers, I know about “sort” packege’s Ints method but unfortunately it accepts only slice of ints


(Norbert Melzer) #2

By wrapping in a very simple type and then implementing sort.Interface for that.

https://play.golang.org/p/o1Jb-hIQXLI


(Rio M) #3

Simpler solution with sort.Slice: https://play.golang.org/p/9s_noUV5sDA


(Norbert Melzer) #4

Nice, I have to remember that one! Would have saved me a lot of lines in a couple of projects…


(Kristoffer Berdal) #5

It’s actually fairly new! Since 1.8 https://golang.org/doc/go1.8#sort_slice


(Johan Dahl) #6

This works fine but a more idiomatic (https://gobyexample.com/sorting-by-functions) way to do it is like this:

https://play.golang.org/p/VUi6dXWB13M

When you coerce your slice into the type byValue and the call to the sort function looks really nice:

sort.Sort(byValue(f))