In this program, we will create a simple map to store country code using the make() function. Then we access and print elements of the map using the range.
The source code to iterate map elements using range is given below. The given program is compiled and executed successfully.
// 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)
}
}
Output:
Map elements:
pak : 104
usa : 105
ind : 101
aus : 102
eng : 103
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. Then we iterate map elements using range and print the KEY and VALUE of map elements on the console screen.
Program/Source Code:
The source code to iterate map elements using range is given below. The given program is compiled and executed successfully.
Output:
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. Then we iterate map elements using range and print the KEY and VALUE of map elements on the console screen.
need an explanation for this answer? contact us directly to get an explanation for this answer