Home  >  Article  >  Backend Development  >  How to Merge Maps in Golang While Avoiding Duplicate Values?

How to Merge Maps in Golang While Avoiding Duplicate Values?

Susan Sarandon
Susan SarandonOriginal
2024-10-27 18:45:01333browse

How to Merge Maps in Golang While Avoiding Duplicate Values?

Merge Maps in Golang

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.

Simple Merge

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.

Avoiding Duplicates

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn