Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to count items in a Go map?

Tags:

go

map

If I want to count the items in the map structure, what statement should I use? I tried to use

for _, _ := range m {...} 

but it seems the syntax is false.

like image 886
shirley Avatar asked Sep 22 '12 14:09

shirley


People also ask

How do you count in Golang?

The Count function counts the number of times a substring appears inside a string . To use this function, you must import the strings package in your file and access the Count function within it using the . notation ( string. Count ).

How to get len of map in Golang?

To get length of map in Go programming, call len() function and pass map as argument to it. The function returns an integer representing the number of key:value pairs in the map.


2 Answers

Use len(m). From http://golang.org/ref/spec#Length_and_capacity

len(s)    string type      string length in bytes           [n]T, *[n]T      array length (== n)           []T              slice length           map[K]T          map length (number of defined keys)           chan T           number of elements queued in channel buffer 

Here are a couple examples ported from the now-retired SO documentation:

m := map[string]int{} len(m) // 0  m["foo"] = 1 len(m) // 1 

If a variable points to a nil map, then len returns 0.

var m map[string]int len(m) // 0 

Excerpted from Maps - Counting map elements. The original author was Simone Carletti. Attribution details can be found on the contributor page. The source is licenced under CC BY-SA 3.0 and may be found in the Documentation archive. Reference topic ID: 732 and example ID: 2528.

like image 61
zzzz Avatar answered Sep 21 '22 10:09

zzzz


For anyone wanting to count the number of elements in a nested map:

  var count int   m := map[string][]int{}   for _, t := range m {     count += len(t)   } 
like image 40
marq Avatar answered Sep 22 '22 10:09

marq