Sorting Arrays in Go: A Practical Guide
James Reed
Infrastructure Engineer · Leapcell

Key Takeaways
- The
sort
package provides built-in functions for sorting slices but not fixed-size arrays directly. - Arrays must be converted to slices before sorting with
sort.Ints
,sort.Strings
, orsort.Float64s
. - Custom sorting can be achieved using the
sort.Interface
for complex data types.
In Go, sorting arrays is a fundamental operation that can be achieved using the standard library's sort
package. This package provides utilities to sort slices, which are more commonly used in Go due to their flexibility compared to arrays. However, since arrays and slices are closely related in Go, sorting an array involves converting it to a slice before applying the sort functions.
Understanding Arrays and Slices in Go
An array in Go is a fixed-size sequence of elements of the same type. For example:
var arr [5]int = [5]int{3, 1, 4, 5, 2}
A slice is a dynamically-sized, flexible view into the elements of an array. Slices are more versatile and are used more frequently in Go programming. A slice can be declared and initialized like this:
var s []int = []int{3, 1, 4, 5, 2}
Sorting a Slice
To sort a slice of integers, you can use the sort.Ints
function from the sort
package:
package main import ( "fmt" "sort" ) func main() { s := []int{3, 1, 4, 5, 2} sort.Ints(s) fmt.Println(s) // Output: [1 2 3 4 5] }
For sorting slices of other types, such as float64
or string
, Go provides sort.Float64s
and sort.Strings
respectively.
Sorting an Array
Since the sort
package functions operate on slices, to sort an array, you need to convert it to a slice first. Here's how you can do it:
package main import ( "fmt" "sort" ) func main() { arr := [5]int{3, 1, 4, 5, 2} sort.Ints(arr[:]) fmt.Println(arr) // Output: [1 2 3 4 5] }
In this example, arr[:]
creates a slice that includes all elements of the array arr
. The sort.Ints
function then sorts this slice in place, which also modifies the original array.
Custom Sorting
For more complex sorting scenarios, such as sorting based on a custom comparator or sorting a struct by one of its fields, you can implement the sort.Interface
interface, which requires the methods Len()
, Less(i, j int) bool
, and Swap(i, j int)
.
Here's an example of sorting a slice of structs by a specific field:
package main import ( "fmt" "sort" ) type Person struct { Name string Age int } type ByAge []Person 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() { people := []Person{ {"Alice", 30}, {"Bob", 25}, {"Charlie", 35}, } sort.Sort(ByAge(people)) fmt.Println(people) }
This will output:
[{Bob 25} {Alice 30} {Charlie 35}]
In this example, we define a Person
struct and a ByAge
type that implements the sort.Interface
for sorting people by age. The sort.Sort
function then sorts the slice according to the Less
method defined for ByAge
.
Conclusion
Sorting in Go is straightforward using the sort
package. While arrays have a fixed size and are less commonly used, slices offer more flexibility and are the standard for collections in Go. By converting arrays to slices, you can leverage Go's powerful sorting functions to organize your data efficiently.
FAQs
No, Go's sort
package only works with slices, so arrays must be converted to slices before sorting.
Use sort.Float64s(slice)
to sort a slice of float64
values in ascending order.
Implement the sort.Interface
methods (Len()
, Less()
, Swap()
) for the struct type and use sort.Sort()
.
We are Leapcell, your top choice for hosting Go projects.
Leapcell is the Next-Gen Serverless Platform for Web Hosting, Async Tasks, and Redis:
Multi-Language Support
- Develop with Node.js, Python, Go, or Rust.
Deploy unlimited projects for free
- pay only for usage — no requests, no charges.
Unbeatable Cost Efficiency
- Pay-as-you-go with no idle charges.
- Example: $25 supports 6.94M requests at a 60ms average response time.
Streamlined Developer Experience
- Intuitive UI for effortless setup.
- Fully automated CI/CD pipelines and GitOps integration.
- Real-time metrics and logging for actionable insights.
Effortless Scalability and High Performance
- Auto-scaling to handle high concurrency with ease.
- Zero operational overhead — just focus on building.
Explore more in the Documentation!
Follow us on X: @LeapcellHQ