go

Declare array of struct literal


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


Solution

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

    Edit: Fixed the brackets