liveBook · Manning

Sort.Slice

As explained in Learn Go with Pocket-Sized Projects

sort.Slice is a Go function that sorts a slice in place according to a supplied less-than comparison function.

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

How Learn Go with Pocket-Sized Projects covers it

How deep it goes
Explains comparator structure, in-place mutation, string-ordering behavior, and the alternative sort.Interface approach.
Examples
Uses books sorted by author and title, plus a common-books result passed through a sorting helper.
What you can do after
Apply it via Go's sort package to sort slices with custom ordering and test the resulting sequence.
How it connects
Connects slices, anonymous functions, sort.Interface, string comparison, and automated testing.

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.