Search code examples
gocomparison

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


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.


Solution

  • 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 Go 1.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 ordered 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
        })
    }
    

    Documentation about slices.Compare:

    Compare compares the elements of s1 and s2. The elements are compared sequentially, starting at index 0, until one element is not equal to the other. The result of comparing the first non-matching elements is returned. If both slices are equal until one of them ends, the shorter slice is considered less than the longer one. The result is 0 if s1 == s2, -1 if s1 < s2, and +1 if s1 > s2. Comparisons involving floating point NaNs are ignored.