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:
package main
import "fmt"
func main() {
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
CopiedMap:= make(map[string] int )
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:
package main
import "fmt"
func main() {
map_1 := map[ int ]string{
90: "Dog" ,
91: "Cat" ,
92: "Cow" ,
93: "Bird" ,
94: "Rabbit" ,
}
map2 := map[string] int {}
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]
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
10 May, 2020
Like Article
Save Article