Sorting

Contents
Sort ints and strings
Sort structs with Less
SortFunc and Find
The slices package

Sort ints and strings

The sort package sorts slices in place, so the call changes the slice instead of returning a copy. Ints orders numbers from small to large, and Strings orders text in byte order.

AreSorted helpers check the order without touching the data. They are handy in tests and in code that must confirm input before running an algorithm that needs sorted data.

package main import ( "fmt" "sort" ) func main() { nums := []int{5, 3, 8, 1} sort.Ints(nums) fmt.Println(nums) names := []string{"go", "c", "python"} sort.Strings(names) fmt.Println(names) fmt.Println(sort.IntsAreSorted(nums)) }

[1 3 5 8]

[c go python]

true

Sort structs with Less

Custom types need three methods to join the sort.Interface family: Len, Less, and Swap. Less carries the ordering rule, while Len and Swap are plain plumbing around the slice.

The example below sorts users by age. The byAge type wraps a user slice, so the original user type stays clean and the ordering rule lives in one small place.

package main import ( "fmt" "sort" ) type user struct { name string age int } type byAge []user func (a byAge) Len() int { return len(a) } func (a byAge) Less(i, j int) bool { return a[i].age < a[j].age } func (a byAge) Swap(i, j int) { a[i], a[j] = a[j], a[i] } func main() { team := []user{{"Ann", 30}, {"Bob", 20}} sort.Sort(byAge(team)) fmt.Println(team) }

[{Bob 20} {Ann 30}]

SortFunc and Find

When a full method set feels heavy, sort.Slice takes the slice plus a small Less function. The closure sees the slice, so the rule stays next to the call that needs it.

sort.Search finds a position inside sorted data with binary search. Give it the length and a function that reports whether the element at an index is large enough, and it returns the first matching index.

package main import ( "fmt" "sort" ) func main() { nums := []int{5, 3, 8, 1} sort.Slice(nums, func(i, j int) bool { return nums[i] < nums[j] }) fmt.Println(nums) at := sort.Search(len(nums), func(i int) bool { return nums[i] >= 5 }) fmt.Println(at) }

[1 3 5 8]

2

The slices package

Since Go 1.21 the slices package offers generic helpers that cover the common cases. Sort replaces Ints and Strings with one function, and helpers such as Contains and IsSorted answer frequent questions in one call.

New code should reach for slices first and fall back to sort only for custom orderings that need an explicit Less function or a stable sort with extra control.

package main import ( "fmt" "slices" ) func main() { nums := []int{5, 3, 8, 1} slices.Sort(nums) fmt.Println(nums) fmt.Println(slices.Contains(nums, 3)) fmt.Println(slices.IsSorted(nums)) }

[1 3 5 8]

true

true

Next: Concurrency patterns

Article author: Arthur Isaev

Related articles
Golang
Go course: zero to hero in 50 lessons
What is Go and where it runs
Install Go and check the version
Your first Go program
Modules with go mod
Variables
Constants
Types
Numbers
Strings
Conditions with if
Switch in Go
Loops with for
Arrays in Go
Slices in Go
Maps in Go
Functions in Go
Errors as values
Pointers in Go
Structs in Go
Methods in Go
Interfaces in Go
Embedding instead of inheritance
Generics in Go
Packages and imports
The go toolchain
Testing with go test
Advanced errors
defer in Go
Strings, bytes and runes
Time in Go
JSON
Files and IO
HTTP servers
HTTP clients
Context
Goroutines
Channels
select and sync
CLI: args, flags, env
Logging
Regular expressions
Sorting
Concurrency patterns
Databases with database/sql
Benchmarks and profiling
Toolchain and CI
Project layout
Capstone: wordfreq CLI
Capstone: JSON API server
Hero roadmap: the whole course on one page
Install Go on Windows 11
Install Go on Ubuntu
Install Go on Rocky Linux
Install Go on macOS
Install Go on FreeBSD
Go in Docker

Search this site

Channel @aofeed Chat @aofeedchat

Contacts and cooperation:
I recommend our hosting beget.ru
Write to info@urn.su, info@aredel.com if you:
1. Want to write an article for our site or translate an article into your native language.
2. Want to place thematically relevant ads on the site.
3. Ads on my site pass maximum censorship. If you see an ad block unsuitable for school-age children, shocking or misleading - please contact us by e-mail
4. Found a mistake, inaccuracy, bug, etc. on the site. ... .......
5. Articles can be shared on social media by clicking a network icon: