Home > database >  How do I sort a slice of slices of something (how do I compare two slices) in Go
How do I sort a slice of slices of something (how do I compare two slices) in Go

Time:06-10

In Go is possible to compare two strings:

package main

func main() {
    println("ab" > "ba")
    println("ab" < "ba")
}
false
true

Program exited.

https://go.dev/play/p/svkLf6R84SC

How do I perform a similar operation on two slices? e.g. []int{1,2} > []int{2,1}.

I need this to sort a slice of slices of ints. So I need an implementation of sort.Interface.

type Interface interface {
    Len() int
    Less(i, j int) bool
    Swap(i, j int)
}

It would be better if this implementation is generic.

CodePudding user response:

Writing a comparator and a less function for sort.Slices would be the most effective way to do this within the standard library. Stepping outside of that slightly (until generics usage within the standard library is finalized), in go1.18 we can use the golang.org/x/exp/constraints and golang.org/x/exp/slices packages to generically sort a slice of slices of comparable values: https://go.dev/play/p/MA0lY6POVFR

func SortSlices[T constraints.Ordered](s [][]T) {
    sort.Slice(s, func(i, j int) bool {
        return slices.Compare(s[i], s[j]) < 0
    })
}
  • Related