How to Merge Maps in Golang While Avoiding Duplicate Values?

Susan Sarandon
Release: 2024-10-27 18:45:01
Original
332 people have browsed it

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!