Go’s sort package makes slice ordering deterministic. sort.Slice accepts a slice and a comparison function; the function reports whether the element at index i belongs before the element at index j. section 3.2.3
Use the package with these design points:
- Separate sorting logic from the main algorithm by wrapping sort.Slice in a focused function. section 3.2.3
- Sort by multiple fields by comparing the primary field first and the secondary field only when needed. section 3.2.3
- Choose between sort.Slice and sort.Interface, which requires Len, Swap, and Less methods. section 3.5
- Remember that sorting modifies the original slice rather than creating a sorted copy. section 3.2.3
Sort books by author and title
func sortBooks(books []Book) []Book { sort.Slice(books, func(i, j int) bool { if books[i].Author != books[j].Author { return books[i].Author < books[j].Author } return books[i].Title < books[j].Title }) return books }
