liveBook · Manning

Sort.Interface

As explained in Learn Go with Pocket-Sized Projects

sort.Interface is a Go interface requiring Len, Less, and Swap methods so a collection can be sorted by the sort package.

sort.Interface lets the sort package order a slice or user-defined collection through three methods: Len, Less, and Swap. All three must be implemented, even when the sorting logic mainly depends on Less. section 3.4.1

Implement the interface on a collection type:

Sort books by author, then title

Define a named slice type such as byAuthor []Book. Its Len method returns len(b), Swap exchanges b[i] and b[j], and Less compares Author first, then Title when authors match. Convert the slice with byAuthor(books), call sort.Sort(byAuthor(books)), and return the same slice after its contents have been reordered. section 3.4.1

Listing 3.22 Implementing sort.Interface on Books
// byAuthor is a list of Book. 
// Defining a custom type to implement sort.Interface
type byAuthor []Book

// Len implements sort.Interface by returning the length of the BookByAuthor.
func (b byAuthor) Len() int { return len(b) } #1

// Swap implements sort.Interface and swaps two books.
func (b byAuthor) Swap(i, j int) { 
    b[i], b[j] = b[j], b[i] #2
}

// Less implements sort.Interface and 
// returns books sorted by Author and then Title.
func (b byAuthor) Less(i, j int) bool {
    if b[i].Author != b[j].Author { #3
        return b[i].Author < b[j].Author
    }
    return b[i].Title < b[j].Title #4
}

View the complete byAuthor implementation, including method receivers and the secondary title comparison. section 3.4.1

How Learn Go with Pocket-Sized Projects covers it

How deep it goes
Defines all three methods and demonstrates chained comparison, but does not detail the sorting algorithm behind sort.Sort.
Examples
Demonstrates sorting a Book slice by Author and then Title with a named byAuthor collection type.
What it assumes
Assumes familiarity with Go slices, methods, indexes, and comparisons while reinforcing collection-based sorting.
What you can do after
Apply it via sort.Sort to reorder a slice using custom collection behavior and multi-field comparisons.
How it connects
Connects sort.Interface with slices, sort.Slice, sort.Sort, and custom sorting.

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 Learn Go with Pocket-Sized Projects. The section links point to the parts of the book it draws on.