Go Gopher How to Go

🏗️

Go's standard library provides robust support for sorting slices and user-defined collections through the sort package. It includes functions for sorting built-in types as well as interfaces for custom sorting logic.

💡 Key Points

  • The sort package provides functions for sorting slices of built-in types like int, float64, and string.
  • Custom sorting can be achieved by implementing the sort.Interface.
  • The sort.Slice function allows sorting slices using a custom less function without defining a new type.
  • Stable sorting is available via sort.Stable, which preserves the order of equal elements.
  • Sorting is done in-place, modifying the original slice.

Basic Sorting Example

This example demonstrates how to sort a slice of integers using the sort package:

package main
import (
  "fmt"
  "sort"
  )

func main() {
  numbers := []int{5, 2, 6, 3, 1, 4}
  fmt.Println("Before sorting:", numbers)
  sort.Ints(numbers)
  fmt.Println("After sorting:", numbers)
}
Output:
Before sorting: [5 2 6 3 1 4]
After sorting: [1 2 3 4 5 6]