声明结构体字面量的数组

18

我该如何声明一个结构体数组字面量?

Go:

type Ping struct {
    Content []aContent
}

type aContent struct {
    Type        string
    Id          string
    Created_at  int64
}

func main() {
    f := Ping{Content: []aContent{Type: "Hello", Id: "asdf"}}
    fmt.Println(f)
}

这里可以找到代码:http://play.golang.org/p/-SyRw6dDUm

2个回答

41
你只需要再加一对括号。
[]aContent{{Type: "Hello", Id: "asdf"}, {Type: "World", Id: "ghij"}}
           ^                                                      ^
         here                                                    and here

那是数组中的一对,每个结构体都有一对。编辑:修复了括号。

0
你实际上忘记传递一个数组(就像@nos所示),而是错误地传递了一个单个对象。我已经将作用域分解以更容易地展示(代码在这里可用):
func main() {
    f := Ping {
        Content: []aContent { //  Start declaring the array of `aContent`s

            { //  Specify a single `aContent`
                Type: "Hello",
                Id:   "object1",
            },

            { //  Specify another single `aContent` if needed
                Type: "World",
                Id:   "object2",
            },
            
        }, //  End declaring the array of `aContent`s
    }
    fmt.Println(f)
}

使用更好的命名

我强烈建议使用更好的命名来减少歧义。例如,通过使用 Contents(带有复数形式的 s),您可以快速确定它是一个数组。而且,您可以将结构体命名为 Content,而不是 aContent(不需要额外的 a 来表示它是一个单个对象)。

因此,重构后的版本将会是 像这样


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接