What is the sort function in Golang?

Golang has a built-in sort function that can be used to sort slices of strings, integers, and floating-point numbers.

Sorting is done using one of these functions:

  • sort.Ints
  • sort.Float64s
  • sort.Strings

sort.Ints

The sort.Ints function sorts a slice of integers in ascending order.

package main
import (
"fmt"
"sort"
)
func main() {
intarray := []int{109, 58, 2, 51, 4, 97} // unsorted
fmt.Println("Before sorting:",intarray)
sort.Ints(intarray)
fmt.Println("After sorting:",intarray)
}

sort.Strings

The sort.Strings function sorts a slice of strings in ascending order.

package main
import (
"fmt"
"sort"
)
func main() {
strarray := []string{"the", "quick", "brown", "fox"} // unsorted
fmt.Println("Before sorting:",strarray)
sort.Strings(strarray)
fmt.Println("After sorting:",strarray)
}

sort.Float64s

The sort.Float64s function sorts a slice of floating-point values in ascending order.

package main
import (
"fmt"
"sort"
)
func main() {
floatarray := []float64{109.32, 109.21, 2.93, 49.23, 4.32, 49.11} // unsorted
fmt.Println("Before sorting:",floatarray)
sort.Float64s(floatarray)
fmt.Println("After sorting:",floatarray)
}

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved