Skip to content

Instantly share code, notes, and snippets.

@stnc
Forked from wuriyanto48/golang_reduce_map.go
Created October 2, 2020 12:08
Show Gist options
  • Save stnc/6a82e10315705c7aa1c1405e9cebaf57 to your computer and use it in GitHub Desktop.
Save stnc/6a82e10315705c7aa1c1405e9cebaf57 to your computer and use it in GitHub Desktop.
How to Join Map In Golang (Map Union)
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