How to combine 2 maps into a third map in Go

1 Answer

0 votes
package main

import (
    "fmt"
)

func main() {
    map1 := map[string]string{
        "A": "aaa",
        "B": "bbb",
    }

    map2 := map[string]string{
        "C": "ccc",
        "B": "XYZ", // Overwrites key "B"
        "D": "ddd",
    }

    combined := make(map[string]string)

    // Copy map1 into combined
    for k, v := range map1 {
        combined[k] = v
    }

    // Merge map2 into combined (overwrites duplicates)
    for k, v := range map2 {
        combined[k] = v
    }

    // Display the result
    for k, v := range combined {
        fmt.Printf("%s => %s\n", k, v)
    }
}



/*
run:

D => ddd
C => ccc
A => aaa
B => XYZ

*/

 



answered Aug 26, 2025 by avibootz
edited Aug 26, 2025 by avibootz

Related questions

1 answer 81 views
1 answer 76 views
76 views asked Aug 7, 2025 by avibootz
2 answers 105 views
1 answer 200 views
2 answers 104 views
...