0
0
GoHow-ToBeginner · 3 min read

How to Use sort.Slice in Go: Syntax and Examples

In Go, sort.Slice sorts a slice based on a custom comparison function you provide. You pass the slice and a function that returns true if the element at index i should come before the element at index j. This lets you easily sort slices without defining a full type implementing sort.Interface.
📐

Syntax

The sort.Slice function takes two arguments: the slice to sort and a less function that compares two elements by their indexes. The less function returns true if the element at index i should be ordered before the element at index j.

  • slice: The slice you want to sort.
  • less: A function with signature func(i, j int) bool that defines the sorting order.
go
sort.Slice(slice, func(i, j int) bool {
    return slice[i] < slice[j]
})
💻

Example

This example shows how to sort a slice of integers in ascending order using sort.Slice. It demonstrates passing the slice and a comparison function that compares elements by their values.

go
package main

import (
	"fmt"
	"sort"
)

func main() {
	numbers := []int{42, 23, 16, 15, 8, 4}

	sort.Slice(numbers, func(i, j int) bool {
		return numbers[i] < numbers[j]
	})

	fmt.Println(numbers)
}
Output
[4 8 15 16 23 42]
⚠️

Common Pitfalls

Common mistakes when using sort.Slice include:

  • Not providing a correct comparison function, which can cause incorrect sorting or runtime errors.
  • Modifying the slice inside the comparison function, which can lead to unpredictable behavior.
  • Using sort.Slice on non-slice types or nil slices.

Always ensure your comparison function is consistent and does not change the slice during sorting.

go
package main

import (
	"fmt"
	"sort"
)

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

	// Wrong: comparison function modifies the slice (DO NOT DO THIS)
	// sort.Slice(numbers, func(i, j int) bool {
	// 	numbers[i], numbers[j] = numbers[j], numbers[i] // modifies slice
	// 	return numbers[i] < numbers[j]
	// })

	// Correct: only compare values
	sort.Slice(numbers, func(i, j int) bool {
		return numbers[i] < numbers[j]
	})

	fmt.Println(numbers)
}
Output
[1 2 3]
📊

Quick Reference

ParameterDescription
sliceThe slice to be sorted
less func(i, j int) boolFunction that returns true if element at i should come before element at j
ReturnsNo return value; sorts slice in place

Key Takeaways

Use sort.Slice to sort slices with a custom comparison function without defining new types.
The comparison function must be consistent and only compare elements without modifying the slice.
sort.Slice sorts the slice in place; it does not return a new slice.
Always pass a valid slice and a less function with signature func(i, j int) bool.
Avoid side effects inside the comparison function to prevent unpredictable results.