Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sorting a uint64 slice in go

Tags:

slice

go

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

like image 679
ufk Avatar asked Jul 27 '16 08:07

ufk


People also ask

How do you sort slices in go?

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.

How would you sort a slice of custom structs?

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.

How does sort slice work Golang?

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.

How do I sort a string in go?

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.


1 Answers

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.

like image 183
vicentazo Avatar answered Oct 04 '22 17:10

vicentazo