liveBook · Manning

Sort package

As explained in Learn Go with Pocket-Sized Projects

sort is Go's standard-library package for sorting slices and other ordered collections.

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 }

How Learn Go with Pocket-Sized Projects covers it

How deep it goes
Explains sort.Slice comparators, multi-field ordering, mutation, and the alternative sort.Interface contract.
Examples
Uses a book collection sorted by author and then title.
What it assumes
Assumes familiarity with slices, indexing, comparisons, functions, and map iteration.
What you can do after
Apply it via sort.Slice to produce deterministic, multi-key ordering for a slice.
How it connects
Connects slices, maps, anonymous functions, and sort.Interface.

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.