英文:
Go, Golang : array type inside struct, missing type composite literal
问题
我需要将切片类型添加到这个结构体中。
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
我该如何修复这个问题?如何构造包含数组(切片)类型的结构体?
英文:
I need to add slice type to this struct.
type Example struct {
text []string
}
func main() {
var arr = []Example {
{{"a", "b", "c"}},
}
fmt.Println(arr)
}
Then I am getting
prog.go:11: missing type in composite literal
[process exited with non-zero status]
So specify the composite literal
var arr = []Example {
{Example{"a", "b", "c"}},
But still getting this error:
cannot use "a" (type string) as type []string in field value
http://play.golang.org/p/XKv1uhgUId
How do I fix this? How do I construct the struct that contains array(slice) type?
答案1
得分: 52
这是你的Example结构体的正确切片:
[]Example{
Example{
[]string{"a", "b", "c"},
},
}
让我解释一下。你想要创建一个Example的切片。所以这里是[]Example{}。然后它必须被填充一个Example——Example{}。而Example又由[]string组成——[]string{"a", "b", "c"}。这只是正确语法的问题。
英文:
Here is your proper slice of Example struct:
[]Example{
Example{
[]string{"a", "b", "c"},
},
}
Let me explain it. You want to make a slice of Example. So here it is — []Example{}. Then it must be populated with an Example — Example{}. Example in turn consists of []string — []string{"a", "b", "c"}. It just the matter of proper syntax.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论