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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1A single less function can encode any number of sort keys by falling through to the next comparison only when values are equal.
- 2Direction is per-field: use less-than for ascending order and greater-than to sort a key like salary descending.
- 3sort.Slice reorders the slice in place, so the caller sees the sorted result without a return value.
Related explainers
go
package streaming import ( "bufio"
Streaming NDJSON logs over HTTP in Go
http-streaming
channels
select
Advanced
10 steps
go
package api import ( "crypto/sha256"
ETag conditional requests in Gin
http-caching
etag
conditional-requests
Intermediate
6 steps
go
func (w *Watcher) resetDebounce(d time.Duration) { if !w.timer.Stop() { select { case <-w.timer.C:
Debouncing a stream of events in Go
debounce
timers
channels
Advanced
7 steps
go
package logging import ( "context"
Deduplicating log attributes in Go's slog
decorator-pattern
structured-logging
immutability
Intermediate
8 steps
go
package middleware import ( "net/http"
Per-plan export limits in Gin middleware
middleware
rate-limiting
authorization
Intermediate
7 steps
python
import re from functools import total_ordering from typing import Optional
Parsing and comparing semantic versions
regex
operator-overloading
sorting
Intermediate
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/multi-key-sorting-in-go-explained-go-320d/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.