go中动态初始化数组大小

go中动态初始化数组大小

问题描述:

我尝试在 go 中编写一个小应用程序,它从标准输入中获取 'x' 个整数,计算平均值并将其返回.我只得到了这么多:

I try to write a small application in go that takes 'x' numbers of integers from standard input, calculates the mean and gives it back. I have only gotten so far:

func main() {
var elems, mean int
sum := 0

fmt.Print("Number of elements? ")

fmt.Scan(&elems)

var array = new([elems]int)

for i := 0; i < elems; i++ {
    fmt.Printf("%d . Number? ", i+1)
    fmt.Scan(&array[i])
    sum += array[i];
}............

尝试编译时,我收到以下错误消息:

When trying to compile this I get the following error message:

无效的数组绑定元素

这里出了什么问题?

你应该使用切片而不是数组:

You should use a slice instead of an array:

//var array = new([elems]int) - no, arrays are not dynamic
var slice = make([]int,elems) // or slice := make([]int, elems)

请参阅go 切片用法和内部结构".

此外,您可能还需要考虑在循环中使用范围:

Also you may want to consider using range for your loop:

// for i := 0; i < elems; i++ { - correct but less idiomatic
for i, v := range slice {