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:
- Len reports the number of elements. section 3.4.1
- Less reports whether element i should appear before element j. section 3.4.1
- Swap exchanges the elements at indexes i and j. section 3.4.1
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

