【问题标题】:Go, Golang : array type inside struct, missing type composite literalGo,Golang:结构内的数组类型,缺少类型复合文字
【发布时间】:2013-10-20 20:39:42
【问题描述】:

我需要给这个结构添加切片类型。

 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

我该如何解决这个问题?如何构造包含数组(切片)类型的结构?

【问题讨论】:

    标签: go


    【解决方案1】:

    这是Example struct 的正确片段:

    []Example{
      Example{
       []string{"a", "b", "c"},
      },
    }
    

    让我解释一下。您想制作Example 的一部分。所以这里是-[]Example{}。然后它必须填充ExampleExample{}Example 又包括 []string[]string{"a", "b", "c"}。这只是正确语法的问题。

    希望对您有所帮助。

    【讨论】:

    • 这个怎么样?它具有更多的价值,并且由于其他原因而不起作用。想不通
    • 如果您不以文字表示法命名字段,则必须为所有字段提供值,否则命名字段。 golang.org/ref/spec#Composite_literals 。基于您的工作示例:play.golang.org/p/13OSJHd5xe
    • 请注意,您不需要第二个Example - go 足够聪明,可以在没有明确命名的情况下找出[]Example 中充满了Example 项目。 Playground
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-08
    • 2017-05-12
    • 1970-01-01
    • 2014-01-12
    • 2021-09-28
    • 1970-01-01
    相关资源
    最近更新 更多