liveBook · Manning

Sort.Interface

As explained in 100 Go Mistakes and How to Avoid Them

The Go sorting interface that defines collection length, element ordering, and element-swapping operations.

A common mistake is treating sort.Interface as a sorting algorithm. It defines the behavior needed to sort an index-based collection while leaving the algorithm and concrete type replaceable. section 2.5.2

type Interface interface {
    Len() int               #1
    Less(i, j int) bool     #2
    Swap(i, j int)          #3
}

Implement Len, Less, and Swap to expose collection size, element ordering, and element exchange. section 2.5.2

Use the abstraction, not the algorithm

Code that depends on sort.Interface can sort different index-based collections without depending on whether the implementation uses merge sort, quicksort, or another algorithm. The same interface also supports utilities such as sort.IsSorted. section 2.5.2

How 100 Go Mistakes and How to Avoid Them covers it

How deep it goes
Defines three required operations and explains reuse, while stopping short of implementing a sorting algorithm.
Examples
Uses Len, Less, and Swap implementations alongside sort.IsSorted as a consumer of the interface.
What you can do after
Apply it via the sort package to support interchangeable collection implementations and sortedness checks.
How it connects
Connects interfaces with abstraction, decoupling, substitutable implementations, and sorting utilities.

Also explained in

Compare how 2 books explain sort.Interface →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 Go Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.