请教go 2个struct运算

fenglangjuxu · · 919 次点击
fenglangjuxu
出售域名 http://letsgo.xin
优雅~ 谢谢了哈
#2
更多评论
你看这样咋样?不知道符合你的优雅不? ``` 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