The sort
package provides these functions for sorting the builtin slice types:
sort.Ints(a []int)
sort.Float64s(a []float64)
sort.Strings(a []string)
It also provides these types for converting the builtin slice types to named types with Len()
, Less()
, Search()
, Sort()
, and Swap()
methods:
sort.IntSlice
sort.Float64Slice
sort.StringSlice
That means I can sort a slice of ints like this...
// Function
slice := []int{5, 4, 3, 2, 1}
sort.Ints(slice) // sort in place
or like this...
// Method
slice := sort.IntSlice{5, 4, 3, 2, 1}
slice.Sort() // also sort in place
Is it preferable to sort with a function or a method? Are there times when one form should be preferred over the other?
The definition of sort.Ints(x)
is literally sort.Sort(sort.IntSlice(x))
so it really doesn't matter. The former is shorter, so I'd use that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With