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
+10.3k Golang : Find and replace data in all files recursively
+4.9k Which content-type(MIME type) to use for JSON data
+5.9k Golang : List all packages and search for certain package
+12.8k Golang : Get absolute path to binary for os.Exec function with exec.LookPath
+12.9k Swift : Convert (cast) Int or int32 value to CGFloat
+7.2k Golang : Get Alexa ranking data example
+10.5k Golang : Generate random integer or float number
+22.3k Golang : Repeat a character by multiple of x factor
+12.9k Golang : flag provided but not defined error
+14.4k Golang : Chunk split or divide a string into smaller chunk example
+7.5k Golang : How to convert strange string to JSON with json.MarshalIndent
+6.4k Apt-get to install and uninstall Golang