How to avoid re-implementing sort.Interface for similar golang structs


There is one problem bothering me in Golang.
Say I have 2 structs:

type Dog struct {
   Name string
   Breed string
   Age int

type Cat struct {
    Name string
    FavoriteFood string
    Age int

And when I try to sort []*Dog and []*Cat by Age, I have to define 2 different sort struct like:

type SortCat []*Cat
func (c SortCat) Len() int {//..}
func (c SortCat) Swap(i, j int) {//..}
func (c SortCat) Less(i, j int) bool {//..}

type SortDog []*Dog
func (c SortDog) Len() int {//..}
func (c SortDog) Swap(i, j int) {//..}
func (c SortDog) Less(i, j int) bool {//..}

A natural thought is to implement some SortableByAge interface and create a Less function using the interface function. Like:

type SortableByAge interface {
    AgeValue() int

And then:

type SortAnimal []SortableByAge
func (c SortDog) Less(i, j int) bool {
    return c[i].AgeValue() < c[j].AgeValue() 

However, according to:

dogs := make([]*Dogs, 0 , 1)
//add dogs here

Above is not possible.

So I wonder what is the best practice for this case and

Is there any other technique that can reduce the need for implementing the sort.Interface for similar structs again and again that I have missed?

I realized that my examples are terrible 🙁

In real life case, these 2 structs are very different, the only thing in common between them is that I wish to sort them by a common numeric value.

A better example would be:

type Laptop {//...}
type Pizza {//...}

And the only thing these 2 structs share in common is that I wish to sort a slice(agh… should not have used Pizza in example) of them by price.

So, combining them to a common struct is not really working for a lot of cases.
But will look into go generate.


Note: as illustrated in commit ad26bb5, in Go 1.8 (Q1 2017), you won’t have to implement Len() and Swap() and Less() since issue 16721 was resolved. Only Less() is needed, the rest is done by reflection.

The problem was:

  1. Vast majority of sort.Interface uses a slice
  2. Have to define a new top level type
  3. Len and Swap methods are always the same
  4. Want to make common case simpler with least hit to performance

See the new sort.go:

// Slice sorts the provided slice given the provided less function.
// The sort is not guaranteed to be stable. For a stable sort, use
// SliceStable.
// The function panics if the provided interface is not a slice.
func Slice(slice interface{}, less func(i, j int) bool) {
    rv := reflect.ValueOf(slice)
    swap := reflect.Swapper(slice)
    length := rv.Len()
    quickSort_func(lessSwap{less, swap}, 0, length, maxDepth(length))

So as long as you have a Less() function comparing two instances respecting an interface, you can sort any number of struct respecting said common interface.

Go 1.18 generics will add another option, as illustrated in nwillc/genfuncs/container/sort.go.

// Sort sorts a slice by the LessThan order.
func (s GSlice[T]) Sort(lessThan genfuncs.BiFunction[T, T, bool]) {
    n := len(s)
    s.quickSort(0, n, maxDepth(n), lessThan)

With BiFunction:

// BiFunction accepts two arguments and produces a result.
type BiFunction[T, U, R any] func(T, U) R

This is just an example illustrating how a generic sort could be implemented: it is not an official one (since generics are, at the ime of writing, Q1 2022, still very new).

Answered By – VonC

Answer Checked By – Gilberto Lyons (GoLangFix Admin)

Leave a Reply

Your email address will not be published.