append
returns a reference to the appended-to slice. This is because it could point to a new location in memory if it needed to be resized.
In your first example, you are updating the variable passed to your setAttribute
function, but that’s it. The only reference is lost when that function exits.
It works in the second example because that variable lives in your struct, and is thus updated.
You can fix the first version by using a pointer:
func (p *ProductInfo) setAttributeData() {
key := "key"
value := "value"
setAttribute(&p.TopAttributes, key, value)
}
func setAttribute(p *[]map[string]interface{}, key string, value interface{}) {
val := map[string]interface{}{
key: value,
}
*p = append(*p, val)
}