Sorting array of Ints

Issue

I’m attempting to sort an array of Ints using the following function

func sortArray(array [100]int) [100]int {
    var sortedArray = array
    sort.Sort(sort.Ints(sortedArray))

    return sortedArray
}

and getting the following error:

.\helloworld.go:22: cannot use sortedArray (type [100]int) as type []int in argument to sort.Ints
.\helloworld.go:22: sort.Ints(sortedArray) used as value

I’m trying to figure out Go and I’m getting stuck on this one.

Solution

You can sort an array by taking a slice of the entire array

sort.Ints(array[:])

You probably don’t want an array in the first place however, and should be using a slice of []int.

Also, your sortedArray is the same value as array, so there is no reason to create the second variable.

Answered By – JimB

Answer Checked By – Mildred Charles (GoLangFix Admin)

Leave a Reply

Your email address will not be published.