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 theme import ( "fmt"
Per-tenant HTML templates with Gin's renderer
multi-tenancy
concurrency
html-templates
Advanced
8 steps
rust
use std::cmp::Ordering; pub struct PrefixIndex { entries: Vec<String>,
Prefix search with binary partitioning in Rust
binary-search
sorting
case-insensitive
Intermediate
7 steps
go
package auth import ( "net/http"
Setting and reading secure session cookies in Go
cookies
session-management
security
Intermediate
6 steps
go
package middleware import ( "net/http"
A maintenance-mode gate in Gin
middleware
atomic-flag
concurrency
Intermediate
8 steps
go
func ServeVideo(c *gin.Context) { id := c.Param("id") video, err := videoRepo.FindByID(c.Request.Context(), id) if err != nil {
Streaming video files with Gin
http streaming
range requests
file serving
Intermediate
6 steps
go
package handler type LineItem struct { SKU string `json:"sku" binding:"required,alphanum"`
Structured validation errors in Gin
validation
json-binding
error-handling
Intermediate
8 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.