Go Pointers – append values to slice via pointer

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

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)