【发布时间】:2016-10-16 13:09:12
【问题描述】:
我有一个结构 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)
}
我想知道它为什么不起作用。我的代码没有错误,但传入的数据是空的。 我试图这样做以使其成为通用函数,因为我有另一个必须以相同方式设置的 BottomAttributes。
【问题讨论】:
-
请给Minimal, Viable, Complete Example. 根据你给我们的代码,这甚至不应该编译。您引用 attrData,您的意思是 attrCode 吗?
-
我已经给出了所需的代码。