Global array in golang

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

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"}

huangapple
  • 本文由 发表于 2015年10月2日 03:08:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/32895042.html
匿名

发表评论

匿名网友

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

确定