Golang : Copy map(hash table) example
Problem:
You have a map and you want to copy the elements to another map. How to do that ?
Solution:
Use for
loop to iterate over the original map and assign the items/elements to a new map.
For example:
package main
import (
"fmt"
)
func main() {
originalMap := map[int]string{
1: "A",
2: "B",
3: "C",
}
copiedMap := map[int]string{}
fmt.Println("BEFORE : ")
fmt.Println("Original Map : ", originalMap)
fmt.Println("Copied Map : ", copiedMap)
// copy map by assigning elements to new map
for key, value := range originalMap {
copiedMap[key] = value
}
// NOTES : Golang map(hash table) elements does not have order
fmt.Println("--------------")
fmt.Println("AFTER : ")
fmt.Println("Original Map : ", originalMap)
fmt.Println("Copied Map : ", copiedMap)
}
Sample outputs:
BEFORE :
Original Map : map[1:A 2:B 3:C]
Copied Map : map[]
AFTER :
Original Map : map[2:B 3:C 1:A]
Copied Map : map[3:C 1:A 2:B] // map does not have order
BEFORE :
Original Map : map[1:A 2:B 3:C]
Copied Map : map[]
AFTER :
Original Map : map[2:B 3:C 1:A]
Copied Map : map[1:A 2:B 3:C]
See also : Golang : Extract or copy items from map based on value
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+81.3k Golang : How to convert character to ASCII and back
+4k Golang : Print instead of building pyramids
+14.4k Chrome : ERR_INSECURE_RESPONSE and allow Chrome browser to load insecure content
+12.8k Golang: Pad right or print ending(suffix) zero or spaces in fmt.Printf example
+9.5k Golang : Interfacing with PayPal's IPN(Instant Payment Notification) example
+14.3k Golang : invalid character ',' looking for beginning of value
+6.3k Android Studio : AlertDialog to get user attention example
+5k Fontello : How to load and use fonts?
+4.6k Python : Print unicode escape characters and string
+4.7k List of Golang XML tutorials
+7.9k Golang : How to extract video or image files from html source code
+9.1k Golang : Get login name from environment and prompt for password