Lesson 17 of 38 · Slices & Maps
Sorting Slices and 2D Slices in Go
A leaderboard is only useful when it's in order, and a game board is a grid of rows and columns. In this lesson you'll sort Go slices — by their natural order or by any rule you like — and build slices of slices for tables and grids.
Sorting basics
The sort package has ready-made functions such as sort.Ints and sort.Strings. The newer slices package offers slices.Sort, which works for any ordered type — numbers and strings:
nums := []int{42, 7, 19, 3}
sort.Ints(nums) // sorts in place, returns nothing
fmt.Println(nums)
names := []string{"cy", "Bo", "ada", "Al"}
slices.Sort(names)
fmt.Println(names)
[3 7 19 42]
[Al Bo ada cy]
Strings are compared byte by byte, so every uppercase letter sorts before every lowercase one.
Custom order
To sort by your own rule, pass a function. sort.Slice takes a less function: less(i, j) reports whether the element at index i belongs before the one at index j.
words := []string{"shield", "gem", "sword"}
sort.Slice(words, func(i, j int) bool {
return len(words[i]) < len(words[j]) // shorter words first
})
fmt.Println(words) // [gem sword shield]
slices.SortFunc takes a comparison function of two elements instead. It returns a negative number when a comes first, a positive number when b comes first, and 0 when they tie. cmp.Compare from the cmp package and strings.Compare return exactly that. Swap the arguments to sort in descending order, and compare a second key when the first one ties:
scores := []int{40, 95, 70}
slices.SortFunc(scores, func(a, b int) int {
return cmp.Compare(b, a) // b before a: descending
})
fmt.Println(scores)
loot := []string{"ruby", "axe", "gold", "bow"}
slices.SortFunc(loot, func(a, b string) int {
if c := cmp.Compare(len(a), len(b)); c != 0 {
return c // shorter first
}
return strings.Compare(a, b) // same length: alphabetical
})
fmt.Println(loot)
[95 70 40]
[axe bow gold ruby]
Sorting happens in place
None of these functions return a new slice. They reorder the elements of the slice you pass in — and because slices share their array, that is the caller's data. When you still need the original order, sort a copy:
arrivals := []int{3, 1, 2}
ranked := slices.Clone(arrivals)
slices.Sort(ranked)
fmt.Println(arrivals, ranked) // [3 1 2] [1 2 3]
Stable sorting
When two elements tie, sort.Slice and slices.SortFunc may put them in either order. A stable sort — sort.SliceStable or slices.SortStableFunc — keeps tied elements in their original order:
names := []string{"Cy", "Ada", "Bo", "Al", "Eve"}
slices.SortStableFunc(names, func(a, b string) int {
return cmp.Compare(len(a), len(b))
})
fmt.Println(names) // [Cy Bo Al Ada Eve]
When the result must be fully predictable, a tie-breaker such as the alphabetical comparison in the loot example works with any sort function.
Slices of slices
A [][]int is a slice whose elements are []int slices — one per row. grid[r][c] reads row r, column c. make([][]int, rows) creates only the outer slice, and every row in it is still nil, so give each row its own array in a loop:
board := make([][]int, 2) // two nil rows
for r := range board {
board[r] = make([]int, 3)
}
board[0][1] = 7
fmt.Println(board, board[0][1])
[[0 7 0] [0 0 0]] 7
Rows don't need the same length. A jagged slice is fine, and nested range loops handle it naturally:
triangle := [][]int{{1}, {1, 1}, {1, 2, 1}}
for r, row := range triangle {
sum := 0
for _, v := range row {
sum += v
}
fmt.Println(r, row, sum)
}
0 [1] 1
1 [1 1] 2
2 [1 2 1] 4
Common mistakes
- Expecting a sorted result:
sorted := sort.Ints(nums)doesn't compile — sort functions return nothing. - Sorting the caller's slice by accident: clone first when the input must stay unchanged.
- Forgetting to create the rows: after
make([][]int, 2),grid[0][1] = 5panics withindex out of range [1] with length 0. - Sharing one row: assigning the same slice to every
grid[r]makes all rows alias one array, so writing to one row changes them all.
Assignment
Rank the arena's champions. None of the functions may modify their input slice.
SortedCopy(nums []int) []intreturns the numbers in ascending order.TopN(scores []int, n int) []intreturns thenhighest scores, highest first. Ifnis larger thanlen(scores), return all of them; ifnis0or negative, return an empty slice.SortByLength(words []string) []stringreturns the words sorted by length, shortest first; words of the same length are sorted alphabetically.MultiplicationTable(n int) [][]intreturns ann×ntable whose rowi, columnjholds(i+1) * (j+1). Forn <= 0, return an empty slice.
SortedCopy([]int{5, -2, 9, 0}) // [-2 0 5 9]
TopN([]int{50, 90, 70, 90, 10}, 3) // [90 90 70]
SortByLength([]string{"sword", "gem", "axe"}) // [axe gem sword]
MultiplicationTable(3) // [[1 2 3] [2 4 6] [3 6 9]]
The starter imports slices. Add cmp, sort or strings to the imports when you use them.
Premium lesson
Unlock the full Learn Go course
- All 38 lessons, bosses and quizzes — lifetime access
- One payment of $35, no subscription
- Finish within 30 days and claim $10.50 (30%) back
Want more than one course?
The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.
Sorting and searching lists in other languages
- JavaScript Array find, some, every and sort · JavaScript
- Python List Methods and Sorting · Python
Need a quick reminder? The Go cheat sheet has every topic of Learn Go on one page.
Lesson last updated on .