Sorting with the Sorter Interface

This lesson provides a detailed code and explanation of an interface designed in a separate package and implemented in the main package.

We'll cover the following

Sorting the data

An excellent example comes from the Go standard library itself, namely the package sort (look up the documentation of this package here).

To sort a collection of numbers or strings, you only need the number of elements Len(), a way to compare items i and j with Less(i, j) and a method to swap items with indexes i and j with Swap(i, j). The Sort-function in sort has an algorithm that only uses these methods on a collection data (to implement it we use here a bubble sort, but any sort-algorithm could be used):

func Sort(data Sorter) {
  for pass:=1; pass < data.Len(); pass++ {
    for i:=0; i < data.Len() - pass; i++ {
      if data.Less(i+1, i) {
        data.Swap(i, i+1)
      }
    }
  }
}

Sort can accept a general parameter of an interface type Interface, which declares these methods:

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

The type int in Interface does not mean that the collected data must contain ints, i and j are integer indices, and the length is also an integer. Note that a type implementing the methods of Interface can be a collection of data of any type.

Now, if we want to be able to sort an array of ints, all we must do is to define a type and implement the methods of Interface. For example, for a type IntSlice the package defines:

type IntSlice []int
func (p IntSlice) Len() int { return len(p) }
func (p IntSlice) Less(i, j int) bool { return p[i] < p[j] }
func (p IntSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }

Here, is the code to call the sort-functionality in a concrete case:

data := []int{74, 59, 238, -784, 9845, 959, 905, 0, 0, 42, 7586, -5467984, 7586}
a := sort.IntSlice(data) //conversion to type IntSlice from package sort
sort.Sort(a)

Get hands-on with 1400+ tech skills courses.