Skip to content

Archive

Sorting

2 articles
Go 11 Sep 2026 6 min read

Sort Struct Slices in Go with slices.SortFunc

Sorting a slice of structs usually starts with a simple requirement such as “priority first, then ID.” The awkward part is expressing that ordering clearly enough that sorting, validation, and binary search can all agree on it. slices.SortFunc handles this directly. You give it the slice and a comparator that defines the order. It sorts the existing slice in place, so there is no separate result to assign. Sort a struct slice with slices.SortFunc Suppose a queue contains jobs that should be ordered by ascending priority and then by ID when priorities match:

Go 11 Sep 2026 6 min read

Check Custom Slice Ordering in Go with slices.IsSortedFunc

Sometimes you need to know whether a slice is already in the right order, not sort it again. That comes up when validating API input, checking an invariant before binary search, or avoiding unnecessary work when records are expected to arrive ordered. For plain numbers and strings, slices.IsSorted handles the common case. When the elements are structs or the ordering is application-specific, slices.IsSortedFunc lets you define exactly what “sorted” means and returns a boolean without rearranging the slice.