Sorting orders a slice according to a comparison function. Go’s sort.Slice accepts the slice and a function that decides whether one indexed item precedes another. section 3.2.3
Use sorting to make collection results predictable and testable:
- Separate sorting logic from the algorithm that finds or transforms data. section 3.2.3
- Remember that sort.Slice modifies the original slice rather than returning a sorted copy. section 3.2.3
- Choose comparison criteria deliberately; string comparisons use UTF encoding, placing Greek titles after Latin titles. section 3.2.3
Books ordered by author, then title
A comparator first compares Author fields and, when they match, compares Title fields. This produces a deterministic book list and simplifies testing. 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
}
The complete Go implementation wraps sort.Slice in sortBooks and returns the reordered slice. section 3.2.3

















