Skip to content
Related Articles

Related Articles

How to copy a map to another map in Golang?
  • Last Updated : 10 May, 2020

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:




// 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)  
    }
}

Output:

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

Example 2:




// 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) 
}

Output:

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



My Personal Notes arrow_drop_up
Recommended Articles
Page :