英文:
Global array in golang
问题
我正在尝试声明一个全局数组,然后稍后进行初始化,像这样:
package main
import (
"fmt"
)
var testStrings []string
func main() {
testStrings = [...]string{"apple","banana","kiwi"}
fmt.Println(testStrings)
}
但是我得到了错误提示:"无法将 3string 字面量(类型为 3string)用作赋值中的 []string 类型"
如何声明全局数组而不指定大小?
英文:
I'm trying to declare a global array and then init it later like so:
package main
import (
"fmt"
)
var testStrings []string
func main() {
testStrings = [...]string{"apple","banana","kiwi"}
fmt.Println(testStrings)
}
But I'm getting error: "cannot use 3string literal (type 3string) as type []string in assignment"
How do I declare global array without specifying size?
答案1
得分: 10
[...]
表示一个数组。
[]
表示一个切片。
修改一个例子,例如:
package main
import (
"fmt"
)
var arrtestStrings [3]string
var slicetestStrings []string
func main() {
arrtestStrings = [...]string{"apple", "banana", "kiwi"}
slicetestStrings = []string{"apple", "banana", "kiwi"}
fmt.Println(arrtestStrings)
fmt.Println(slicetestStrings)
}
英文:
[...]
means an array.
[]
means a slice.
Change one. For example:
package main
import (
"fmt"
)
var arrtestStrings [3]string
var slicetestStrings []string
func main() {
arrtestStrings = [...]string{"apple", "banana", "kiwi"}
slicetestStrings = []string{"apple", "banana", "kiwi"}
fmt.Println(arrtestStrings)
fmt.Println(slicetestStrings)
}
答案2
得分: 7
根据Go规范:
> ...
表示数组长度等于最大元素索引加一。
这对你的代码不起作用,因为 testStrings
是一个slice,而不是一个array(请阅读有关数组和切片之间的区别的文章)。删除 ...
将修复你的程序:
testStrings = []string{"apple","banana","kiwi"}
英文:
From the Go specification:
> The notation ...
specifies an array length equal to the maximum element index plus one.
This does not work for your code because testStrings
is a slice, not an array (read about the difference between arrays and slices). Dropping the ...
will fix your program:
testStrings = []string{"apple","banana","kiwi"}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论