Dong.Ge

左手代码 右手江湖

golang struct 运算(拙劣的表演和优雅的实现)

东哥's Avatar 2019-05-31

  1. 目的就是,计算wcd1,wcd2两个结构体,如果uid相同,num,num1经行累加,否则就不用累加,保留原有的数值.
  2. 拙劣的表演

目的就是,计算wcd1,wcd2两个结构体,如果uid相同,num,num1经行累加,否则就不用累加,保留原有的数值.

拙劣的表演

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
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,
},
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,
},
}
Build(wcd1, wcd2)
}
func Build(list ...[]Item) {
totalList := []Item{}
for _, one := range list {
totalList = append(totalList, one...)
}
/*
wcd := append(wcd1, wcd2...)
fmt.Println(wcd)
*/
okok := map[int]map[string]int{}
for _, one := range totalList {
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
}
}
returnOk := []Item{}
for uid, one := range okok {
returnOk = append(returnOk, Item{
Uid: uid,
Num: one["num"],
Num1: one["num1"],
})
}
//fmt.Printf("%#v", returnOk)
for _, one := range returnOk {
fmt.Println("uid:", one.Uid, "num:", one.Num, "num1:", one.Num1)
}
}

优雅的实现(求助于场外网友)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
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,
},
}

returnOk := PlusStruct(wcd1, wcd2)
for _, one := range returnOk {
fmt.Println("uid:", one.Uid, "num:", one.Num, "num1:", one.Num1)
}
}
本文最后更新于 天前,文中所描述的信息可能已发生改变