英文:
Dynamically initialize array size in go
问题
我试图用Go语言编写一个小应用程序,从标准输入中获取'x'个整数,计算平均值并返回。我只做到了这一步:
func main() {
var elems, mean int
sum := 0
fmt.Print("元素的数量?")
fmt.Scan(&elems)
var array = new([elems]int)
for i := 0; i < elems; i++ {
fmt.Printf("%d . 数字?", i+1)
fmt.Scan(&array[i])
sum += array[i];
}............
尝试编译时,我收到以下错误信息:
无效的数组边界 elems
这里有什么问题?
英文:
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:
> invalid array bound elems
What is wrong here?
答案1
得分: 153
你应该使用切片而不是数组:
//var array = new([elems]int) - 不行,数组不是动态的
var slice = make([]int,elems) // 或者 slice := make([]int, elems)
参考“go slices usage and internals”。另外,你可能想考虑在循环中使用range:
// for i := 0; i < elems; i++ { - 正确但不太惯用
for i, v := range slice {
英文:
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)
See "go slices usage and internals". 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 {
答案2
得分: 22
在我看来,这是由于对<code>new</code>和<code>make</code>函数的使用产生了混淆。这是Go语言中已知的问题/特性,可以通过关于<code>new</code>和<code>make</code>的几次讨论来证明,这些讨论可以在golang-nuts中找到。
通过让Go打印出<code>new</code>和<code>make</code>创建的值的类型,可以更清楚地了解它们之间的区别:
package main
import "fmt"
func main() {
fmt.Printf("%T %v\n", new([10]int), new([10]int))
fmt.Printf("%T %v\n", make([]int, 10), make([]int, 10))
}
输出结果:
*[10]int &[0 0 0 0 0 0 0 0 0 0]
[]int [0 0 0 0 0 0 0 0 0 0]
从类型可以看出,要访问<code>new([10]int)</code>的数组元素,我们首先需要解引用指针。
<code>new</code>和<code>make</code>都需要一个Go类型作为它们的第一个参数。然而,表达式<code>[elems]int</code> 不是一个Go类型(除非<code>elems</code>是一个Go常量,在这里不是这种情况)。
有关更多参考,请参阅http://golang.org/doc/go_spec.html#Allocation和http://golang.org/doc/go_spec.html#The_zero_value。
为了更好地理解<code>new</code>的结果是否可用,可以查找<code>len</code>和<code>cap</code>是否适用于零(nil)值:http://golang.org/doc/go_spec.html#Length_and_capacity
英文:
In my opinion, this results from confusion over the usage of the <code>new</code> and <code>make</code> functions. This is a known issue/feature in the Go language, as evidenced by several discussions about <code>new</code> vs <code>make</code> at golang-nuts.
The difference between <code>new</code> and <code>make</code> may become clearer by letting Go print out the type of the value created by <code>new</code> and <code>make</code>:
package main
import "fmt"
func main() {
fmt.Printf("%T %v\n", new([10]int), new([10]int))
fmt.Printf("%T %v\n", make([]int, 10), make([]int, 10))
}
The output:
*[10]int &[0 0 0 0 0 0 0 0 0 0]
[]int [0 0 0 0 0 0 0 0 0 0]
As can be seen from the type, to access an array element of <code>new([10]int)</code> we would first need to dereference the pointer.
Both <code>new</code> and <code>make</code> require a Go type as their 1st argument. However, the expression <code>[elems]int</code> is not a Go type (unless <code>elems</code> is a Go constant, which isn't the case here).
For further reference, see http://golang.org/doc/go_spec.html#Allocation and http://golang.org/doc/go_spec.html#The_zero_value.
To get a better understanding of whether the result of <code>new</code> is usable, it may be helpful to lookup whether <code>len</code> and <code>cap</code> work with zero (nil) values: http://golang.org/doc/go_spec.html#Length_and_capacity
答案3
得分: 4
请参阅Go编程语言规范
http://golang.org/ref/spec#Array_types
http://golang.org/ref/spec#Constants
它说:“长度是数组类型的一部分;它必须评估为一个非负的常量,可以用int类型的值表示。”
常量绝对不会变化。
英文:
See The Go Programming Language Specification
http://golang.org/ref/spec#Array_types
http://golang.org/ref/spec#Constants
It says:"The length is part of the array's type; it must evaluate to a non- negative constant representable by a value of type int. "
Constants by no means vary.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论