How to Find Length of Map in Go: Simple Guide
In Go, you can find the length of a map using the built-in
len() function. Simply pass your map variable to len(), and it returns the number of key-value pairs in the map.Syntax
The syntax to find the length of a map in Go is simple:
len(mapVariable): Returns the number of key-value pairs in the map.
Here, mapVariable is your map variable.
go
length := len(mapVariable)Example
This example shows how to create a map, add some key-value pairs, and find its length using len().
go
package main import "fmt" func main() { fruits := map[string]string{ "a": "Apple", "b": "Banana", "c": "Cherry", } length := len(fruits) fmt.Println("Number of items in map:", length) }
Output
Number of items in map: 3
Common Pitfalls
Some common mistakes when finding the length of a map in Go include:
- Trying to use
len()on anilmap, which returns 0 but the map is unusable for storing values. - Confusing the length of a map with the length of its keys or values separately.
- Expecting
len()to count nested elements inside map values (it only counts top-level pairs).
go
package main import "fmt" func main() { var myMap map[string]int // nil map fmt.Println(len(myMap)) // Outputs 0, but map is nil and cannot store values myMap = make(map[string]int) myMap["x"] = 10 fmt.Println(len(myMap)) // Outputs 1 }
Output
0
1
Quick Reference
Remember these points when working with map length in Go:
len(map)returns the count of key-value pairs.- Length of a
nilmap is 0. - Length does not count nested elements inside map values.
Key Takeaways
Use the built-in len() function to get the number of key-value pairs in a map.
len() returns 0 for nil maps, but nil maps cannot store values.
len() counts only top-level pairs, not nested elements inside values.
Always initialize maps before adding elements to avoid nil map errors.