Go - slice sorting example

In this example, we will show you how to sort a slice in Go with an example.

Go contains the sort package to sort slices.

Go - slice sorting example

In the example, we sort a slice of days and integers.


package main

import (
    "fmt"
    "sort"
)

func main() {

    days := []string{"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"}
    vals := []int{4, 2, 1, 5, 6, 8, 0, -3}

    sort.Strings(days)
    sort.Ints(vals)

    fmt.Println(days)
    fmt.Println(vals)
}

Output:

[Friday Monday Saturday Sunday Thursday Tuesday Wednesday]
[-3 0 1 2 4 5 6 8]