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.
len(map)
This function takes a map as a parameter.
It will return the length of the map that is passed to it.
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)}
In the code snippet above, we do the following:
fmt
, which is used to format the input and output.main()
function in Golang.fruits
, where the key is of data type string and value is of data type int.fruits
using the function len()
and pass the map fruits
as a parameter to it, then assign the returned length to l
.l
of the map fruits
.