## 目的就是,计算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)
}
}
```
你看这样咋样?不知道符合你的优雅不?
```
package main
import "fmt"
type Item struct {
Uid int
Num int
Num1 int
}
func PlusStruct(item1 []Item, item2 []Item) (sli []Item) {
item1 = append(item1, item2...)
plusmap := make(map[int]Item)
for _, v := range item1 {
plusmap[v.Uid] = Item{Uid: v.Uid, Num: plusmap[v.Uid].Num + v.Num, Num1: plusmap[v.Uid].Num1 + v.Num1}
}
for _, v := range plusmap {
sli = append(sli, v)
}
return sli
}
func main() {
wcd1 := []Item{
Item{
Uid: 1,
Num: 1,
Num1: 1,
},
Item{
Uid: 2,
Num: 2,
Num1: 1,
},
Item{
Uid: 5,
Num: 0,
Num1: 99,
},
Item{
Uid: 1,
Num: 1,
Num1: 87,
},
}
wcd2 := []Item{
Item{
Uid: 1,
Num: 1,
Num1: 1,
},
Item{
Uid: 3,
Num: 1,
Num1: 1,
},
Item{
Uid: 3,
Num: 1,
Num1: 10,
},
Item{
Uid: 1,
Num: 4,
Num1: 7,
},
Item{
Uid:2,
Num:3,
Num1:4,
},
}
fmt.Println(PlusStruct(wcd1, wcd2))
}
```
#1