🧮 Sort a string slice containing numbers in Go

sort slice strings

If you have a slice or an array of strings that contain numbers in your Go application, and you want to sort them in natural order instead of alphabetical order, you need to write your own sorting function using the sort.Slice(). It should convert each element to int or float type and make a number comparison. The result will be a slice of the strings sorted like numbers.

Sort in natural order

package main

import (
    "fmt"
    "log"
    "sort"
    "strconv"
)

func sortNumbers(data []string) ([]string, error) {
    var lastErr error
    sort.Slice(data, func(i, j int) bool {
        a, err := strconv.ParseInt(data[i], 10, 64)
        if err != nil {
            lastErr = err
            return false
        }
        b, err := strconv.ParseInt(data[j], 10, 64)
        if err != nil {
            lastErr = err
            return false
        }
        return a < b
    })
    return data, lastErr
}

func main() {
    data := []string{"10", "1", "2", "8", "4", "3", "9", "7", "6", "5"}

    sorted, err := sortNumbers(data)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(sorted)
}

Output:

[1 2 3 4 5 6 7 8 9 10]

As you can see in the sortNumber() function, we return the last error of the two elements comparison. If a given element cannot be converted to a number, it means that the input data is invalid, and the result of sorting may be incorrect. You should handle this error in your application to avoid unexpected results.

Sort in alphabetical order

However, if your goal is to sort the strings alphabetically, just use the sort.Strings() function:

package main

import (
    "fmt"
    "sort"
)

func main() {
    data := []string{"10", "1", "2", "8", "4", "3", "9", "7", "6", "5"}
    sort.Strings(data)
    fmt.Println(data)
}

Output:

[1 10 2 3 4 5 6 7 8 9]

🖨️ Convert string to []byte or []byte to string in Go

Learn the difference between a string and a byte slice
introduction strings slice

🍕 Compare two slices in Go

Learn how to check if two slices are equal
introduction slice strings

🧑‍🤝‍🧑 Copy a slice in Go

Learn how to make a deep copy of a slice
introduction slice