Golang program to create a copy of the map

Here, we are going to learn how to create a copy of the map in Golang (Go Language)?
Submitted by Nidhi, on March 24, 2021 [Last updated : March 04, 2023]

How to create a copy of the map in Golang?

Problem Solution:

In this program, we will create a simple map to store country code using the make() function. Then we create a copy of the map and print both maps on the console screen.

Program/Source Code:

The source code to create a copy of the map is given below. The given program is compiled and executed successfully.

Golang code to create a copy of the map

// Golang program to create a copy of the map

package main

import "fmt"

func main() {
	var CountryCode = make(map[string]int)

	CountryCode["ind"] = 101
	CountryCode["aus"] = 102
	CountryCode["eng"] = 103
	CountryCode["pak"] = 104
	CountryCode["usa"] = 105

	var CloneMap = CountryCode

	fmt.Println("CountryCode: ", CountryCode)
	fmt.Println("CloneMap   : ", CloneMap)
}

Output:

CountryCode:  map[aus:102 eng:103 ind:101 pak:104 usa:105]
CloneMap   :  map[aus:102 eng:103 ind:101 pak:104 usa:105]

Explanation:

In the above program, we declare the package main. The main package is used to tell the Go language compiler that the package must be compiled and produced the executable file. Here, we imported the fmt package to formatting related functions.

In the main() function, we created a CountryCode map using make() function to store country code of specified country. Map store items in KEY/VALUE pair. Then we create a copy of the CountryCode map using the assignment operator and then print both maps on the console screen.

Golang Maps Programs »





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.