Go语言,Golang:结构体内的数组类型,缺少类型复合字面量。

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

Go, Golang : array type inside struct, missing type composite literal

问题

我需要将切片类型添加到这个结构体中。

  1. type Example struct {
  2. text []string
  3. }
  4. func main() {
  5. var arr = []Example {
  6. {{"a", "b", "c"}},
  7. }
  8. fmt.Println(arr)
  9. }

然后我得到了以下错误:

  1. prog.go:11: missing type in composite literal
  2. [process exited with non-zero status]

所以需要指定复合字面量:

  1. var arr = []Example {
  2. {Example{"a", "b", "c"}},
  3. }

但是仍然出现以下错误:

  1. 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.

  1. type Example struct {
  2. text []string
  3. }
  4. func main() {
  5. var arr = []Example {
  6. {{"a", "b", "c"}},
  7. }
  8. fmt.Println(arr)
  9. }

Then I am getting

  1. prog.go:11: missing type in composite literal
  2. [process exited with non-zero status]

So specify the composite literal

  1. var arr = []Example {
  2. {Example{"a", "b", "c"}},

But still getting this error:

  1. 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结构体的正确切片:

  1. []Example{
  2. Example{
  3. []string{"a", "b", "c"},
  4. },
  5. }

让我解释一下。你想要创建一个Example的切片。所以这里是[]Example{}。然后它必须被填充一个Example——Example{}。而Example又由[]string组成——[]string{"a", "b", "c"}。这只是正确语法的问题。

英文:

Here is your proper slice of Example struct:

  1. []Example{
  2. Example{
  3. []string{"a", "b", "c"},
  4. },
  5. }

Let me explain it. You want to make a slice of Example. So here it is — []Example{}. Then it must be populated with an ExampleExample{}. Example in turn consists of []string[]string{"a", "b", "c"}. It just the matter of proper syntax.

huangapple
  • 本文由 发表于 2013年10月21日 04:39:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/19482612.html
匿名

发表评论

匿名网友

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

确定