0
0
GoHow-ToBeginner · 4 min read

How to Sort Slice in Go: Simple Guide with Examples

In Go, you can sort a slice using the sort package. For slices of basic types like int or string, use sort.Ints(slice) or sort.Strings(slice). For custom sorting, use sort.Slice(slice, func(i, j int) bool { ... }).
📐

Syntax

Go provides built-in functions to sort slices of common types and a flexible way to sort slices with custom logic.

  • sort.Ints(slice []int): Sorts a slice of integers in ascending order.
  • sort.Strings(slice []string): Sorts a slice of strings alphabetically.
  • sort.Slice(slice interface{}, less func(i, j int) bool): Sorts any slice using a custom comparison function.
go
import "sort"

// Sort integers
sort.Ints(myIntSlice)

// Sort strings
sort.Strings(myStringSlice)

// Sort any slice with custom logic
sort.Slice(mySlice, func(i, j int) bool {
    return mySlice[i] < mySlice[j]
})
💻

Example

This example shows how to sort a slice of integers and a slice of strings using the built-in functions, and how to sort a slice of structs by a field using sort.Slice.

go
package main

import (
	"fmt"
	"sort"
)

type Person struct {
	Name string
	Age  int
}

func main() {
	ints := []int{5, 3, 8, 1, 2}
	strings := []string{"banana", "apple", "cherry"}
	people := []Person{
		{"Alice", 30},
		{"Bob", 25},
		{"Charlie", 35},
	}

	// Sort integers
	sort.Ints(ints)
	fmt.Println("Sorted ints:", ints)

	// Sort strings
	sort.Strings(strings)
	fmt.Println("Sorted strings:", strings)

	// Sort people by Age
	sort.Slice(people, func(i, j int) bool {
		return people[i].Age < people[j].Age
	})
	fmt.Println("People sorted by age:", people)
}
Output
Sorted ints: [1 2 3 5 8] Sorted strings: [apple banana cherry] People sorted by age: [{Bob 25} {Alice 30} {Charlie 35}]
⚠️

Common Pitfalls

Common mistakes when sorting slices in Go include:

  • Trying to sort slices without importing the sort package.
  • Using sort.Slice but providing a wrong or inconsistent comparison function, which can cause unexpected results.
  • Modifying the slice while sorting, which can lead to race conditions in concurrent programs.

Always ensure your comparison function defines a strict ordering (no ties that break transitivity).

go
package main

import (
	"fmt"
	"sort"
)

func main() {
	nums := []int{3, 1, 2}

	// Wrong: no import or wrong function
	// sort.IntSlice(nums) // This does not sort

	// Wrong: inconsistent comparison (not recommended)
	sort.Slice(nums, func(i, j int) bool {
		return nums[i] > nums[j]
	})

	fmt.Println(nums) // Output may be unexpected

	// Right way: consistent comparison
	sort.Slice(nums, func(i, j int) bool {
		return nums[i] < nums[j]
	})
	fmt.Println("Sorted correctly:", nums)
}
Output
[3 1 2] Sorted correctly: [1 2 3]
📊

Quick Reference

FunctionDescription
sort.Ints([]int)Sorts a slice of integers in ascending order
sort.Strings([]string)Sorts a slice of strings alphabetically
sort.Slice(slice, func(i, j int) bool)Sorts any slice using a custom comparison function

Key Takeaways

Use the sort package to sort slices easily in Go.
For basic types, use sort.Ints or sort.Strings for simple sorting.
Use sort.Slice with a comparison function for custom sorting logic.
Ensure your comparison function is consistent to avoid unexpected results.
Always import the sort package before sorting slices.