Home » How to Find Map Length in Golang

How to Find Map Length in Golang

Golang map is a built-in type that implements a hash table and stores the data in key-value pair.

To find map length in golang, use the len() function and pass the map as an argument. It returns an integer value.

To create a go map, use the below syntax:

map[KeyType] ValueType

Where,

KeyType – any type

ValueType – any type including another map as well.

In this article, we will discuss how to find the length of a map in golang.

How to Find the Map Length using Len() in Golang

Use the len() function and pass the map object to get the length of a map in golang.

package main

import (
	"fmt"
)

func main() {

	// Create a map in go using the make function

	score := make(map[string]int)

	// Add elements to map
	score["Alex"] = 94
	score["Gary"] = 75
	score["Mary"] = 67

	// Get the map lengh
	fmt.Println("Map Length: ", len(score))
	fmt.Println("Print the element of map: ", score)
}

The output of the above Golang program gets the map length.

Map Length:  3

Print the element of map:  map[Alex:94 Gary:75 Mary:67]

To get map length, follow the below steps:

  1. Create a map using the make() function. It creates and initializes a map
  2. Adds elements to the map e.g. score["Alex"] = 94
  3. Get map length using len() function. e.g. len(score)

Cool Tip: How to delete a key from a map in Golang!

How to Get the Length of the Map in Golang

Golang map may contain elements or it can be empty. Before we do any operation on the map, it’s always preferable to check the length of the map.

package main

import (
	"fmt"
)

func main() {

	// Create a map in go using the make function

	var my_map = map[string]int{}

	// Find the lenth of map
	fmt.Println("Lenth of map: ", len(my_map))
	fmt.Println("Print the element of map: ", my_map)

}

The output of the above golang program is:

Lenth of map:  0
Print the element of map:  map[]

In the above program, the map[string]int{} expression creates a map but it’s an empty map.

Cool Tip: How to use struct as keys in the Golang map!

Conclusion

I hope the above article on how to find the length of a map using the len() function is helpful to you.

You can find more topics about the Golang tutorials on the GolangSpot Home page.

Leave a Comment