Copy a Map
Lesson 18 of 21 in Coddy's Slices and Maps in Golang course.
Similar to what we did with slices, we can copy a map and add new values to it.
Let's consider a map like this:
products := map[string]int{
"MacBook": 5000,
"iPhone": 1000,
"Vision pro": 3000,
}Suppose we need to copy the products map:
list := productsThis operation will create a copy of the products map to list. However, the issue arises when changes made to one map will affect the other, as they share the same memory space. We can verify this by printing their memory addresses:
fmt.Printf("%p \n", list)
fmt.Printf("%p", products)The output is as follows:
0xc00010e0c0
0xc00010e0c0The solution here is to use the make keyword. We first declare a map using the make keyword:
list := make(map[string]int)Now, the question you may ask is, what is the difference between using make or just a simple declaration like this:
list := map[string]int{}Actually, there is no difference except that using make, we can define a length for the map.
list := make(map[string]int, len(products))Here, we define the length to be the length of the map that we want to copy.
Note: The length in a map is not like in a slice. Even if we define a length, we can exceed it with no problems.
Now, after defining our new map, we can achieve this using a loop to copy elements from products to the list map:
list := make(map[string]int, len(products))
for key, value := range products {
list[key] = value
}The result will be:
map[Golang Book:400 Python Book:300 Rust Book:500]Now, if we modify one map, it will not affect the other one.
Challenge
EasyIn the given code, we define a map of products called productByName:
- Create a new map called productByPrice.
- Copy elements from the productByName map, but in the opposite way: the price will be the key, and the name will be the value.
- Print both maps to the screen.
Try it yourself
package main
import "fmt"
func main() {
// Define a map of products by name Don't Change this!
productByName := map[string]int{
"MacBook": 5000,
"iPhone": 1000,
"Vision Pro": 3000,
}
// Create a new map of products by price
// Copy elements from productByName to productByPrice
// Print both maps to the screen
fmt.Println("By Name:", )
fmt.Println("By Price:", )
}All lessons in Slices and Maps in Golang
1Introduction
Introduction