我需要给这个结构添加 slice 类型。
type Example struct {
text []string
}
func main() {
var arr = []Example {
{{"a", "b", "c"}},
}
fmt.Println(arr)
}
然后我得到了
prog.go:11: missing type in composite literal
[process exited with non-zero status]
所以指定复合字面量
var arr = []Example {
{Example{"a", "b", "c"}},
但仍然出现此错误:
cannot use "a" (type string) as type []string in field value
http://play.golang.org/p/XKv1uhgUId
我该如何解决这个问题?如何构造包含数组( slice )类型的结构?
最佳答案
这是您正确的 Example
结构片段:
[]Example{
Example{
[]string{"a", "b", "c"},
},
}
让我解释一下。你想制作一个 Example
的片段。所以这里是 - []Example{}
。然后必须用 Example
— Example{}
填充它。 Example
依次由 []string
— []string{"a", "b", "c"}
组成。这只是正确语法的问题。
希望对您有所帮助。
关于Go, Golang : array type inside struct, 缺少类型复合文字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19482612/