1 回答
TA贡献1833条经验 获得超4个赞
坦克的评论,有2个可能的答案:
定义
pairs
为var pairs Pairs
哪个在定义Pairs
而不是pairs := new(Pairs)
哪个在定义*Pairs
pairs
赋值两边的取消引用为:*pairs = append(*pairs, Pair{k, v})
所以现在对我来说完整的工作代码是:
package main
import "fmt"
type Inventory struct { //instead of: map[string]map[string]Pairs
Warehouse string
Item string
Batches Pairs
}
type Pairs []Pair
type Pair struct {
Key string
Value float64
}
func main() {
fmt.Println("Hello, 世界")
var inventory = Inventory{} // or: new(Inventory) noth are working //warehouse[item[batch, qty]]
inventory.Warehouse = "DMM"
inventory.Item = "Helmet"
inventory.Batches = append(inventory.Batches, Pair{"Jan", 10})
inventory.Batches = append(inventory.Batches, Pair{"Jan", 30})
inventory.Batches = append(inventory.Batches, Pair{"Feb", 30})
fmt.Printf("%v\n", inventory)
result := inventory.Batches.group()
fmt.Printf("%v %T\n", result, result)
}
func (p *Pairs) group() Pairs {
sum := make(map[string]float64)
pairs := new(Pairs)
// var pairs Pairs
for _, el := range *p {
sum[el.Key] = sum[el.Key] + el.Value
}
for k, v := range sum {
*pairs = append(*pairs, Pair{k, v}) // with pairs := new(Pairs)
// pairs = append(pairs, Pair{k, v}) // var pairs Pairs
}
return *pairs
}
输出是:
Hello, 世界
{DMM Helmet [{Jan 10} {Jan 30} {Feb 30}]}
[{Jan 40} {Feb 30}] main.Pairs
Program exited.
- 1 回答
- 0 关注
- 139 浏览
添加回答
举报