Home >Backend Development >Golang >How to Merge Maps in Golang and Handle Duplicate Values?
Merging multiple maps with the same key type into a single map requires merging their values for matching keys. In Golang, map values can be any type, including slices.
A simple approach to merge maps is to create a function that iterates over the input maps and appends values to a slice for matching keys in the result map.
<code class="go">func merge(ms ...map[string]string) map[string][]string { res := map[string][]string{} for _, m := range ms { for k, v := range m { res[k] = append(res[k], v) } } return res }</code>
If duplicate values for the same key should be avoided, the merge function can be extended with a check before appending:
<code class="go">func merge(ms ...map[string]string) map[string][]string { res := map[string][]string{} for _, m := range ms { srcMap: for k, v := range m { for _, v2 := range res[k] { if v == v2 { continue srcMap } } res[k] = append(res[k], v) } } return res }</code>
Consider the following maps:
<code class="go">m1 := map[string]string{"id_1": "val_1"} m2 := map[string]string{"id_2": "val_2"} m3 := map[string]string{"id_1": "val_3"}</code>
Using the merge function to merge them produces the following result map:
<code class="go">res := merge(m1, m2, m3) fmt.Println(res)</code>
Output:
map[id_1:[val_1 val_3] id_2:[val_2]]
The above is the detailed content of How to Merge Maps in Golang and Handle Duplicate Values?. For more information, please follow other related articles on the PHP Chinese website!