我有一个struct ProductData及其实例p,它有一个Slice属性:
type ProductInfo struct {
TopAttributes []map[string]interface{}
}
我想按如下方式设置TopAttributes
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)
}
但这似乎并不管用.
但是,当我定义方法时,还有另一种方法可以很好地工作,如下所示:
func (p *ProductInfo) setAttributeData() {
key := "key"
value := "value"
p.setAttribute(key, value)
}
func (p *ProductInfo) setAttribute(key string, value interface{}) {
val := map[string]interface{}{
key: value,
}
p.TopAttributes = append(p.TopAttributes, val)
}
我想找出它为什么不工作.我的代码中没有错误,但是传入的数据是空的. 我try 这样做是为了使它成为一个泛型函数,因为我还有另一个必须以相同方式设置的BottomAttributes.