Sort Go Struct Slices with slices.SortFunc
Sorting a slice of structs usually starts with a field: priority, timestamp, name, score, or some combination of them. slices.Sort can’t handle a struct because a struct has no built-in ordering relation. slices.SortFunc fills that gap by taking a comparator that defines the order for the element type. The call is compact, but the comparator is part of the program’s correctness. It has to describe a consistent ordering, and equal comparisons need deliberate handling when records have multiple fields. This article builds that comparator from simple cases to multi-field ordering and covers the mutation and stability details that tend to cause surprises.