Merging Maps in Golang
Combining multiple maps into a single merged map in Golang is a common task. Suppose you have three maps:
The goal is to merge these maps based on the id key, resulting in:
Simple Merge
To merge the maps, you can iterate over each input map and append the values associated with each key to a slice 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>
Avoiding Duplicates
In some cases, you may want to avoid duplicate values in the merged map. To achieve this, check for duplicates 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 { // Check if (k,v) was added before: for _, v2 := range res[k] { if v == v2 { continue srcMap } } res[k] = append(res[k], v) } } return res }</code>
Usage Example
<code class="go">m1 := map[string]string{"id_1": "val_1"} m2 := map[string]string{"id_2": "val_2", "id_1": "val_1"} m3 := map[string]string{"id_1": "val_3"} 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 avoid duplicate values?. For more information, please follow other related articles on the PHP Chinese website!