-
-
Save stnc/6a82e10315705c7aa1c1405e9cebaf57 to your computer and use it in GitHub Desktop.
How to Join Map In Golang (Map Union)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
) | |
type Item struct{ | |
Id int | |
Name string | |
Qty int | |
} | |
type Maps map[int]Item | |
func ReduceItem(m1, m2 Maps) Maps { | |
for ia, va := range m1 { | |
if it, ok := m2[ia]; ok { | |
va.Qty += it.Qty | |
} | |
m2[ia] = va | |
} | |
return m2 | |
} | |
func main() { | |
m1 := Maps{3: {3, "Wury", 1,}, 5: {5, "Sam", 1,}} | |
m2 := Maps{1: {1, "Alex", 1,}, 2: {2, "Ben", 1, }, 3: {3, "Wury", 1,}, 4: {4, "Lara", 2,}} | |
r := ReduceItem(m2, m1) | |
fmt.Println(r) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment