Saturday, May 24, 2025
HomeGolangKind a string slice containing numbers in Go (Golang)

Kind a string slice containing numbers in Go (Golang)



You probably have a slice or an array of strings that include numbers in your Go utility, and also you wish to kind them in pure order as a substitute of alphabetical order, you could write your personal sorting operate utilizing the kind.Slice(). It ought to convert every aspect to int or float sort and make a quantity comparability. The consequence will likely be a slice of the strings sorted like numbers.

Kind in pure order

bundle essential

import (
    "fmt"
    "log"
    "kind"
    "strconv"
)

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

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

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

Output:

As you may see within the sortNumber() operate, we return the final error of the 2 components comparability. If a given aspect can’t be transformed to a quantity, it signifies that the enter knowledge is invalid, and the results of sorting could also be incorrect. You must deal with this error in your utility to keep away from sudden outcomes.

Kind in alphabetical order

Nevertheless, in case your aim is to kind the strings alphabetically, simply use the kind.Strings() operate:

bundle essential

import (
    "fmt"
    "kind"
)

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

Output:

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments