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
+19.3k Golang : Fix cannot download, $GOPATH not set error
+10.5k Golang : ISO8601 Duration Parser example
+16.2k Golang : convert string or integer to big.Int type
+9.7k Random number generation with crypto/rand in Go
+11k How to test Facebook App on localhost ?
+8.7k Golang : Get final balance from bit coin address example
+10.4k Golang : Meaning of omitempty in struct's field tag
+6.1k Golang : Get missing location after unmarshal binary and gob decode time.
+6.5k Golang : How to determine if request or crawl is from Google robots
+5.2k PHP : Hide PHP version information from curl
+5.7k Golang : Struct field tags and what is their purpose?
+15.7k Golang : How to login and logout with JWT example