0

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.

1
  • 1
    You have to add the identical json tags as well to the anonymous struct. Commented Jul 17, 2020 at 2:29

1 Answer 1

3

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) 
Sign up to request clarification or add additional context in comments.

1 Comment

that worked like charm. Didn't know the field tags had to do with that, I thought they were only like decorative (for information purposes only). Thanks

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.