I need to sort a slice of a type that is coming from a 3rdparty package. Based on some condition the order must be ascending or descending.
The solution I come up with is:
type fooAscending []foo func (v fooAscending) Len() int { return len(v) } func (v fooAscending) Swap(i, j int) { v[i], v[j] = v[j], v[i] } func (v fooAscending) Less(i, j int) bool { return v[i].Amount < v[j].Amount } type fooDescending []foo func (v fooDescending) Len() int { return len(v) } func (v fooDescending) Swap(i, j int) { v[i], v[j] = v[j], v[i] } func (v fooDescending) Less(i, j int) bool { return v[i].Amount > v[j].Amount } if someCondition { sort.Sort(fooAscending(array)) } else { sort.Sort(fooDescending(array)) }
Is there a better way to do this. 13 lines of code for this task and most of it is duplicated, seems a bit too much.
As of Go 1.8, there is an easier way to sort a slice that does not require you to define new types. 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.
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.
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 Go 1.8, there is an easier way to sort a slice that does not require you to define new types. You simply pass an anonymous function to the sort.Slice
function.
a := []int{5, 3, 4, 7, 8, 9} sort.Slice(a, func(i, j int) bool { return a[i] < a[j] }) for _, v := range a { fmt.Println(v) }
This will sort in ascending order, if you want the opposite, simply write a[i] > a[j]
in the anonymous function.
You're looking for sort.Reverse
. That will let you say:
sort.Sort(sort.Reverse(fooAscending(s)))
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