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 main
import(
"fmt"
)
//program execution starts here
func main(){
//declare and initialize a map
fruits := map[string]int{
"orange":20,
"apple":24,
"guava":43,
"watermelon":10,
}
//calculate the length of the map
l := len(fruits)
//display the length
fmt.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 fruits using the function len() and pass the map fruits as a parameter to it, then assign the returned length to l.
  • Line 22: We display the length l of the map fruits.

Free Resources