go 23 lines · 6 steps

Multi-key sorting in Go

A single comparator chains four tie-breaking rules to sort employees by department, salary, and name.

Explained by highlit
1type Employee struct {
2 Department string
3 LastName string
4 FirstName string
5 Salary int
6}
7 
8func sortEmployees(employees []Employee) {
9 sort.Slice(employees, func(i, j int) bool {
10 a, b := employees[i], employees[j]
11 
12 if a.Department != b.Department {
13 return a.Department < b.Department
14 }
15 if a.Salary != b.Salary {
16 return a.Salary > b.Salary
17 }
18 if a.LastName != b.LastName {
19 return a.LastName < b.LastName
20 }
21 return a.FirstName < b.FirstName
22 })
23}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1A single less function can encode any number of sort keys by falling through to the next comparison only when values are equal.
  2. 2Direction is per-field: use less-than for ascending order and greater-than to sort a key like salary descending.
  3. 3sort.Slice reorders the slice in place, so the caller sees the sorted result without a return value.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Multi-key sorting in Go — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code