sort.Slice sorts a slice in place using a supplied less-than function. The comparison can express multiple keys, such as author followed by title, while an anonymous function keeps task-specific ordering close to the call. section 3.2.3
Listing 3.18 bookworm.go: Sorting the books
// sortBooks sorts the books by Author and then Title.
func sortBooks(books []Book) []Book {
sort.Slice(books, func(i, j int) bool { #1
if books[i].Author != books[j].Author {
return books[i].Author < books[j].Author #2
}
return books[i].Title < books[j].Title #2
})
return books
}
Sort books by Author first, then Title when authors match; the function returns the modified slice. section 3.2.3
Account for these practical details:
- The original slice changes; sort.Slice does not create a sorted copy, so mutation may be useful or undesirable. section 3.2.3
- Use sort.Slice directly with a comparison function, or implement sort.Interface with Len, Swap, and Less methods. section 3.5
- Comparing strings with < follows UTF encoding, so Greek titles appear after Latin titles in the stated example. section 3.2.3
Separating sorting from the algorithm that finds common books makes the result easier to test; expected-result order may need adjustment after sorting. section 3.2.3
