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

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

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 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:

确定