Module 4 · Lesson 5 of 520/50 in the course~10 min
Module lessons (5/5)
Sorting with the sort package
Lesson preview5 hands-on exercises readyCourse Go · Module 4 — Collections
sort.Ints, sort.Strings, sort.Slice with comparison function, stability.
What you'll learn in this lesson
- Sort slices of primitive types (
sort.Ints,sort.Strings) and slices of complex structs (sort.Slice,sort.SliceStable). - Write error-free multi-key comparators and descending sorts on the
less(i, j)contract. - Use the new generic type-safe functions from the
slicespackage (Go 1.21+):slices.Sortandslices.SortFunc.
Overview
Sorting in Go acts in-place directly on the passed slice, without allocating a new one. Alongside the historic sort package, from Go 1.21 the generic package slices offers a faster and reflection-free alternative.
sort.Slice does not guarantee that two elements with the same key will retain their original relative position. When that order matters, use sort.SliceStable:
Sections covered in this lesson
- 1Primitive helpers vs
sort.Sliceon struct - 2Stability with
sort.SliceStableand binary search - 3The generic package
slices(Go 1.21+) - 4Slice search sorted with
slices.BinarySearch - 5Guided practice
- 6Check for understanding
Pro Lesson · Module 4 — Collections
Unlock "Sorting with the sort package" and the full Course Go curriculum
`sort.Ints`, `sort.Strings`, `sort.Slice` with comparison function, stability.
Unlock all 5 hands-on exercises in this lesson plus every advanced WebAssembly module with automated checks.
- Instant access to all advanced modules in Course Go plus 17 more courses
- Hands-on browser exercises with automated test suites and solutions
- 14-day money-back guarantee processed via Paddle.com
14-day guarantee · Cancel anytimeModule 1, all 18 interactive games, and cheatsheets are always free.