Golang length of map [2 Easy Methods]

In this tutorial we will explore different methods we can use to get length of map in golang.

 

Different methods to get golang length of map

Method-1: Use the len() function

map is an unordered collection of key-value pairs, where each key is unique. In Go programming, use the len() function and pass the map as an argument to get the length of a map.

Advertisement

In this example, we will learn how to use the len() function to get the length of a given map:

Syntax: The syntax to find the length of Map x is:

len(x)
The function returns an integer indicating how many key-value pairs are in the map. In the following example, we'll count the items in the map studentRecord, where the student name is a key and the score is a value.

package main

import (
	"fmt"
)

func main() {

	//initialize a map
	scoreRecord := map[string]float64{
		"Ariana": 8.6,
		"Bob":    9.3,
		"Clover": 7.8,
		"Daniel": 9,
	}

	//calculate the length of the map
	mapLength := len(scoreRecord)

	//display the length
	fmt.Println("Map is:", scoreRecord)
	fmt.Println("Length of map :", mapLength)
}

Output:

Map is: map[Ariana:8.6 Bob:9.3 Clover:7.8 Daniel:9]
Length of map : 4

Explanation

  • Firstly, declare and initialize the map, where the key is of data type string and value is of data type int.
  • Calculate the length of the map using thelen() length and pass the map as a parameter to it, then assign the returned length to mapLength.
  • Print out the map and the length mapLength of the map.

 

Method-2: Iterate over the map to count all elements in a nested map

We can use range statement to iterate over the map and count the number of elements in a nested map.

Advertisement
package main

import "fmt"

func main() {

	//initialize a nested map
	scoreRecord := map[string][]float64{
		"Ariana": []float64{5.3, 7.3, 6.9},
		"Bob":    []float64{8.3, 8.7, 9.2},
		"Clover": []float64{7.6, 9.2},
		"Daniel": []float64{8.8, 9.0, 8.9},
	}

	//initialize a counter
	counter := 0
	for _, v := range scoreRecord {
		// add up the number of elements in nested map
		counter += len(v)
	}

	fmt.Println("Number of elements in nested map is:", counter)
}

Output:

Number of elements in nested map is: 11

 

Summary

In this Golang Tutorial, we learned how to find the length of a Map, using two different methods:

  • Using len() function
  • Iterate over the map to count the elements

 

References

Golang for loop
Golang maps
Golang length of map

 

Didn't find what you were looking for? Perform a quick search across GoLinuxCloud

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can either use the comments section or contact me form.

Thank You for your support!!

Leave a Comment

X