ADVERTISEMENT
ADVERTISEMENT

Golang program to count the items of a map

Here, we are going to learn how to count the items of a map in Golang (Go Language)?
Submitted by Nidhi, on March 24, 2021

Problem Solution:

In this program, we will create a simple map to store country code using the make() function. Then we find the length of the specified map using the len() function. The len() function returns the total number of stored elements in a specified map.

Program/Source Code:

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

// Golang program to count the items of a map

package main

import "fmt"

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

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

	fmt.Println("Length of CountryCode: ", len(CountryCode))
	delete(CountryCode, "pak")
	fmt.Println("Length of CountryCode: ", len(CountryCode))
}

Output:

Length of CountryCode:  5
Length of CountryCode:  4

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 count the total number of items of the CountryCode map and then print the result on the console screen.

Golang Maps Programs »



ADVERTISEMENT


ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.