undefinedfix
Sign in

Go merges sturct

neal_utas edited in Tue, 27 Sep 2022

A structure is defined

type TotalIssue struct {
    IssueType string `json:"issue_type"`
    Count     int    `json:"count"`
    Donecount int `json:"donecount"`
}

Finally, two results are obtained as follows

[{QA 10 0} {OPS 7 0} {RDC 14 0} {TEST 1 0} {WWW 22 0}]
[{OPS 0 2} {TEST 0 1} {WWW 0 18}]

I want to merge the above results into

[{QA 10 0} {OPS 7 2} {RDC 14 0} {TEST 1 1} {WWW 22 18}]
3 Replies
zcnfk
commented on Wed, 28 Sep 2022
    arr1 := []TotalIssue{{IssueType: "QA", Count: 10, Donecount: 1}, {IssueType: "QC", Count: 10, Donecount: 1}}
    arr2 := []TotalIssue{{IssueType: "QB", Count: 12, Donecount: 2}}
    arr3 := append(arr1, arr2...) //必须加后面三个点
jawalking
commented on Wed, 28 Sep 2022
  • Provide totalissue with a hashkey and merge method to generate unique identification
  • Define a set type and provide add and toArray methods
  • Traverse two lists separately, using set . Add to add to the set

As follows:

type Set struct {
    d map[string]*TotalIssue
}

func (s *Set) Add(item *TotalIssue) {
    if v, ok := s.d[item.hashKey()]; ok {
        v.merge(item)
    } else {
        s.d[item.hashKey()] = item
    }
}

func (s *Set) ToArray() []*TotalIssue {
    arr := make([]*TotalIssue, len(s.d))
    // ... get item from d
    return 
}
NRin
commented on Wed, 28 Sep 2022

There is no good way, two traversal.

lock This question has been locked and the reply function has been disabled.