整理整数数组

huangapple go评论128阅读模式
英文:

Sorting array of Ints

问题

我正在尝试使用以下函数对一个整数数组进行排序:

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

    return sortedArray
}

但是我得到了以下错误:

.\helloworld.go:22: 无法将类型为 [100]int 的 sortedArray 用作 sort.Ints 的参数类型 []int
.\helloworld.go:22: sort.Ints(sortedArray) 用作值

我正在尝试弄清楚 Go 语言,但在这个问题上卡住了。

英文:

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.

答案1

得分: 7

你可以通过对整个数组进行切片来对数组进行排序:

sort.Ints(array[:])

然而,你可能不需要使用数组,而应该使用[]int的切片。

另外,你的sortedArrayarray的值相同,所以没有必要创建第二个变量。

英文:

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.

答案2

得分: 0

你可能根本不需要一个数组,而应该使用一个 []int 的切片。

另外,你的 sortedArray 和 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.

huangapple
  • 本文由 发表于 2017年2月9日 05:01:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/42123515.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定