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
+6.7k Golang : How to execute code at certain day, hour and minute?
+18.7k Golang : Accept input from user with fmt.Scanf skipped white spaces and how to fix it
+22.8k Golang : How to validate URL the right way
+9.3k Golang : Allow Cross-Origin Resource Sharing request
+12k Golang : Linear algebra and matrix calculation example
+8.5k Golang : Copy map(hash table) example
+17.7k Golang : Read input from console line
+4.8k Golang : Use NLP to get sentences for each paragraph example
+8.9k Golang : Compare files modify date example
+6.4k Golang : How to convert strange string to JSON with json.MarshalIndent
+9.9k Golang : Intercept and process UNIX signals example
+7.9k Golang : What is the default port number for connecting to MySQL/MariaDB database ?