Skip to content
Home » How to iterate map elements using the range in Golang

How to iterate map elements using the range in Golang

Learn about How to iterate map elements using the range in Golang in the below code example. Also refer the comments in the code snippet to get a detailed view about what’s actually happening.

How to iterate map elements using the range in Golang

// Golang program to iterate map elements
// using the range

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

	fmt.Printf("\nMap elements: ")
	for Key, Value := range CountryCode {
		fmt.Printf("\n%s : %d", Key, Value)
	}
}

In the above program, we declare the package main. The main package instructs the Go language compiler that the package must be compiled and an executable file generated. We imported the fmt package, which contains the files of the fmt package, and then we can use a function related to the fmt package.

Hope above code works for you and Refer the below Related Codes to gain more insights. Happy coding and come back again.

Similar Codes :
How to create a copy of the map in Golang
How to count the items of a map in Golang