How do I declare an array of struct literal?
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)
}
The code can be found here: http://play.golang.org/p/-SyRw6dDUm
A struct literal denotes a newly allocated struct value by listing the values of its fields. You can list just a subset of fields by using the Name: syntax. (And the order of named fields is irrelevant.)
A structure may contain elements of different data types – int, char, float, double, etc. It may also contain an array as its member. Such an array is called an array within a structure. An array within a structure is a member of the structure and can be accessed just as we access other elements of the structure.
You just need another pair of braces.
[]aContent{{Type: "Hello", Id: "asdf"}, {Type: "World", Id: "ghij"}}}
^ ^
here and here
That's one pair for the array, one for each struct in the array..
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With