I'm writing Go application using Go 1.7rc3.
I have a slice of uint64 (var dirRange []uint64
) that I want to sort.
the sort package has a function sort.Ints()
but it requires []int
and I have []uint64
.
what do I do? can I type cast the all slice ?
thanks
In Go language, you can sort a slice with the help of Slice() function. This function sorts the specified slice given the provided less function. The result of this function is not stable. So for stable sort, you can use SliceStable.
Sort with custom comparatorUse the function sort. Slice . It sorts a slice using a provided function less(i, j int) bool . To sort the slice while keeping the original order of equal elements, use sort.
You simply pass an anonymous function to the sort. Slice function. This will sort in ascending order, if you want the opposite, simply write a[i] > a[j] in the anonymous function. @LewisChan it is not restricted on int types; the int parameters are indexes to the slice, which can be a slice of strings.
To sort a slice of strings in Go programming, use sort package. sort package offers sorting for builtin datatypes and user defined datatypes, through which we can sort a slice of strings. The sorting or strings happen lexicographically. Meaning a is less than b , b is less than c , and so on.
As of version 1.8, you can use the simpler function sort.Slice
. In your case, it would be something like the following:
sort.Slice(dirRange, func(i, j int) bool { return dirRange[i] < dirRange[j] })
This avoids having to define any type just for the sorting.
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