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
+16.4k Golang : Get the IPv4 and IPv6 addresses for a specific network interface
+12.6k Golang : Convert IPv4 address to packed 32-bit binary format
+9.2k Golang : Convert(cast) string to int64
+9.2k Golang : Get all countries currencies code in JSON format
+6.7k Golang : Levenshtein distance example
+12.8k Golang : List objects in AWS S3 bucket
+26.3k Golang : Encrypt and decrypt data with AES crypto
+35.9k Golang : Validate IP address
+26.5k Golang : Find files by extension
+23.7k Golang : Call function from another package
+6.1k Golang : Break string into a slice of characters example
+19k Golang : Delete item from slice based on index/key position