Go, Golang : array type inside struct, 缺少类型复合文字

标签 go

我需要给这个结构添加 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{}。然后必须用 ExampleExample{} 填充它。 Example 依次由 []string[]string{"a", "b", "c"} 组成。这只是正确语法的问题。

希望对您有所帮助。

关于Go, Golang : array type inside struct, 缺少类型复合文字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19482612/

相关文章:

go - 计数增加 2,期望 1

go - 有什么方法可以检查 Go 程序中未处理的错误吗?

go - golang安装覆盖包时出现的问题

戈朗 : Parse bit values from a byte

go - 我的神经网络(从头开始)训练,让它离目标更远

go - 在 Go 中转换 int 和 int64 时得到不同的输出;是由于处理器架构吗?

windows - 忽略 vendor 目录

go - 如何阻止 go html/template 转义路径(尝试过 .HTML .JS 等)

go - 函数末尾缺少返回

go - 在golang中一起验证struct的两个字段