Home >Backend Development >Golang >How to Merge Maps in Golang While Avoiding Duplicate Values?
In Golang, merging multiple maps requires consideration of the desired result map's value type, as the merged values may encompass multiple values associated with the same key. To achieve this, it is recommended to use a slice as the value type for the result map.
To perform a simple merge, the provided sample code can be revised to append values from source maps to the slice associated with the same key 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>
In this example, ms is a variadic parameter, allowing the passing of any number of maps to the merge function.
To filter out duplicates and ensure that values are listed only once in the result map, the code can be modified as follows:
<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>
Here, before appending a value to the result map, the code checks if the (key, value) pair has been previously added, preventing duplicates.
The above is the detailed content of How to Merge Maps in Golang While Avoiding Duplicate Values?. For more information, please follow other related articles on the PHP Chinese website!