How to copy a map to another map in Golang?

Maps in Golang is a collection of unordered pairs of key-value. It is widely used because it provides fast lookups and values that can retrieve, update, or delete with the help of keys. In Map, you can copy a map to another map using the for loop provided by the Go language. In for loop, we fetch the index value 1 by 1 with the element and assign it to another map.

Syntax:

for key, value := range originalMap{
}

Let us discuss this concept with the help of the examples:

Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Go program to illustrate how to 
// copy a map to another map 
  
package main 
    
import "fmt"
    
func main() { 
    
    // Creating and initializing a map 
    // Using shorthand declaration and 
    // using map literals 
    originalMap := make(map[string]int)
    originalMap["one"] = 1
    originalMap["two"] = 2
    originalMap["three"] = 3
    originalMap["four"] = 4
    originalMap["five"] = 5
    originalMap["six"] = 6
    originalMap["seven"] = 7
    originalMap["eight"] = 8
    originalMap["nine"] = 9
      
       
    // Creating empty map 
    CopiedMap:= make(map[string]int)
      
    /* Copy Content from Map1 to Map2*/
    for index, element  := range originalMap{        
         CopiedMap[index] = element
    }
      
    for index, element  := range CopiedMap{ 
        fmt.Println(index, "=>", element)  
    }
}

chevron_right


Output:

seven => 7
eight => 8
two => 2
four => 4
three => 3
six => 6
nine => 9
one => 1
five => 5

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Go program to illustrate how to 
// copy a map to another map 
  
package main 
    
import "fmt"
    
func main() { 
    
    // Creating and initializing a map 
    // Using shorthand declaration and 
    // using map literals 
    map_1 := map[int]string{ 
        
            90: "Dog"
            91: "Cat"
            92: "Cow"
            93: "Bird"
            94: "Rabbit"
    
       
    // Creating and initializing empty map 
    map2 := map[string]int{} 
      
    /* Copy Content from Map1 to Map2*/
    for key, value := range map_1{        
         map2[value] = key
    }
      
    fmt.Println("Copied Map :", map2) 
}

chevron_right


Output:

Copied Map : map[Bird:93 Rabbit:94 Dog:90 Cat:91 Cow:92]



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.