How to Merge Maps in Golang and Handle Duplicate Values?

Linda Hamilton
Release: 2024-10-29 07:10:03
Original
900 people have browsed it

How to Merge Maps in Golang and Handle Duplicate Values?

Merge Maps in Golang

Merging Maps

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.

Custom Merge Function

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

Avoiding Duplicates

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

Example Usage

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

Using the merge function to merge them produces the following result map:

<code class="go">res := merge(m1, m2, m3)
fmt.Println(res)</code>
Copy after login

Output:

map[id_1:[val_1 val_3] id_2:[val_2]]
Copy after login

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!

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!