Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declare array of struct literal

Tags:

go

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

like image 634
user3918985 Avatar asked Sep 24 '14 07:09

user3918985


People also ask

What is a struct literal?

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.)

Can a struct be an array?

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.


1 Answers

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

like image 163
nos Avatar answered Sep 30 '22 21:09

nos