user3918985
user3918985

Reputation: 4409

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

Upvotes: 18

Views: 17575

Answers (2)

nos
nos

Reputation: 229058

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

Upvotes: 41

Mojtaba Hosseini
Mojtaba Hosseini

Reputation: 119108

You actually forgot to pass an array (as @nos showed) an passing a single object by mistake. I have braked down the scopes to show it more easily (the code is available here):

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

💡 Use better naming

I highly recommend to use better naming to reduce ambiguity. For example by using Contents (with the plural s) you can quickly determine that is an Array. And you can name the struct as Content instead of aContent. (no need for extra a to show that is a single object)

So the refactored version would be like this

Upvotes: 0

Related Questions