How to Find Length of Map in Golang

To find the length of a map in Golang, you can use the “len()” function. The len() function returns an integer representing the number of “key: value pairs” in the map.

Syntax

len(x)

Parameters

x: It is a map.

Return value

It returns an integer which is the length of a map.

Example

package main

import "fmt"

func main() {
  // Create a map with string keys and int values
  mainMap := map[string]int{
    "bmw": 1,
    "audi": 2,
    "mercedez": 3,
  }

  // Find the length of the map using the len() function
  mapLength := len(mainMap)

  fmt.Println("Length of the map:", mapLength)
}

Output

Length of the map: 3

You can see that we created a map called “mainMap” with string keys and int values.

In the next step, we found the length of the map using the “len()” function and stored the result in the mapLength variable.