Ad space (banner)
๐ŸนGo Lessons
Lesson 11 / 68

Sorting a Slice

In this lesson you will learn to sort a slice with the sort package, a basic operation you will use constantly in practice. This is for anyone searching for "Go sort how to use".

The standard library's sort package makes reordering a slice easy. Sorting shows up daily in web applications too, for ranking displays and ordering search results.

The sample code sorts a slice of integers into ascending order with sort.Ints(nums). Beyond numbers and strings, sort.Slice lets you order any data at all by a comparison rule you write yourself.

A common stumbling block for beginners is that sort.Ints() rewrites the original slice in place. It does not hand back a new sorted slice, so make a copy first if you need to keep the original data.

In real-world development you pick the function that fits: sort.Strings for a slice of strings, sort.Slice for a slice of structs.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Go directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)