## 目的就是,计算wcd1,wcd2两个结构体,如果uid相同,num,num1经行累加,否则就不用累加,保留原有的数值.
### 以下是我现在的实现
#### 思路是把struct转换成map,然后做运算.然后再吧map转换成struct.
#### 目的是达到了,但是觉得实现的不够优雅?
```golang
package main
import (
"fmt"
)
type Item struct {
Uid int
Num1 int
Num int
}
func main() {
wcd1 := []Item{
Item{
Uid: 1,
Num: 1,
Num1: 1,
},
Item{
Uid: 2,
Num: 2,
Num1: 1,
},
}
wcd2 := []Item{
Item{
Uid: 1,
Num: 1,
Num1: 1,
},
Item{
Uid: 3,
Num: 1,
Num1: 1,
},
Item{
Uid: 3,
Num: 1,
Num1: 10,
},
}
wcd := append(wcd1, wcd2...)
okok := map[int]map[string]int{}
for _, one := range wcd {
if _, ok := okok[one.Uid]; ok == false {
okok[one.Uid] = make(map[string]int)
}
if _, ok := okok[one.Uid]["num"]; ok {
okok[one.Uid]["num"] += one.Num
} else {
okok[one.Uid]["num"] = one.Num
}
if _, ok := okok[one.Uid]["num1"]; ok {
okok[one.Uid]["num1"] += one.Num1
} else {
okok[one.Uid]["num1"] = one.Num1
}
}
fmt.Println(okok)
returnOk := []Item{}
for uid, one := range okok {
returnOk = append(returnOk, Item{
Uid: uid,
Num: one["num"],
Num1: one["num1"],
})
}
for _, one := range returnOk {
fmt.Println("uid:", one.Uid, "num:", one.Num, "num1:", one.Num1)
}
}
```
有疑问加站长微信联系(非本文作者)