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 is used to return an integer representing the number of “key: value pairs” in the 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.

Finally, we printed the length of the map to the console.

Leave a Comment