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")

Program exited.

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.


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 and packages to generically sort a slice of slices of comparable values:

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

Answered By – JimB

Answer Checked By – Katrina (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.