我有一个结构 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。
呼唤远方
侃侃无极
Smart猫小萌
相关分类