How to get the length of a map in Golang
Overview
In this shot, we will learn how to get the length of a map in Golang.
A map is an unordered collection of key-value pairs, where each key is unique.
We can find the length of the map using the len() function provided by Golang.
Syntax
len(map)
Parameters
This function takes a map as a parameter.
Return value
It will return the length of the map that is passed to it.
Example
In the following example, we’ll count the items present in the map fruits, where the fruit name serves as a key, and the number of fruits serves as a value in the map.
package mainimport("fmt")//program execution starts herefunc main(){//declare and initialize a mapfruits := map[string]int{"orange":20,"apple":24,"guava":43,"watermelon":10,}//calculate the length of the mapl := len(fruits)//display the lengthfmt.Println(l)}
Explanation
In the code snippet above, we do the following:
- Line 4: We import the format package
fmt, which is used to format the input and output. - Line 8: The program execution starts from the
main()function in Golang. - Line 11: We declare and initialize the map
fruits, where the key is of data type string and value is of data type int. - Line 19: We calculate the length of the map
fruitsusing the functionlen()and pass the mapfruitsas a parameter to it, then assign the returned length tol. - Line 22: We display the length
lof the mapfruits.