HerbertRedford
HerbertRedford

Reputation: 270

Append struct to anonymous slice of structs in Go

I'm working with a defined struct such as this one:

type MyList struct {
    Items  []struct {
        ResourceLocation string `json:"resourceLocation"`
        Resource         Tmp  `json:"resource"`
    } `json:"items"`
    ListOptions
}

and I need to add a struct to Items slice.

I tried the following:

tmp2 := struct {
            ResourceLocation string
            Resource         Tmp
        }{
            Resource:   myTempStruct,
        }

        tmpList.Items = append(MyList.Items, tmp)

but I'm getting a:

Cannot use 'tmp' (type struct {...}) as type struct {...}

error.

By the way, I cannot modify

type MyList struct {
    Items  []struct {
        ResourceLocation string `json:"resourceLocation"`
        Resource         Tmp  `json:"resource"`
    } `json:"items"`
    ListOptions
}

that's the reason why I cannot assign a name to Items and define it in a separate struct. Thanks.

Upvotes: 0

Views: 505

Answers (1)

Thundercat
Thundercat

Reputation: 120969

The code in the question does not work because field tags are part of the type.

Add the field tags to the anonymous type in the question:

item := struct {
    ResourceLocation string `json:"resourceLocation"`
    Resource         Tmp    `json:"resource"`
}{
    Resource: myTempStruct,
}

Better yet, declare a type with same underlying type as an element of MyList.Items.

type Item struct {
    ResourceLocation string `json:"resourceLocation"`
    Resource         Tmp    `json:"resource"`
}

Use that type when constructing the element:

item := Item{Resource: myTempStruct}
list.Items = append(list.Items, item)

Upvotes: 3

Related Questions