snippetgoCritical
How to count items in a Go map?
Viewed 0 times
itemshowcountmap
Problem
If I want to count the items in the map structure, what statement should I use?
I tried to use
but it seems the syntax is false.
I tried to use
for _, _ := range m {...}but it seems the syntax is false.
Solution
Use
Here are a couple examples ported from the now-retired SO documentation:
If a variable points to a
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.
len(m). From http://golang.org/ref/spec#Length_and_capacitylen(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 bufferHere are a couple examples ported from the now-retired SO documentation:
m := map[string]int{}
len(m) // 0
m["foo"] = 1
len(m) // 1If a variable points to a
nil map, then len returns 0.var m map[string]int
len(m) // 0Excerpted 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.
Code Snippets
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 bufferm := map[string]int{}
len(m) // 0
m["foo"] = 1
len(m) // 1var m map[string]int
len(m) // 0Context
Stack Overflow Q#12544641, score: 242
Revisions (0)
No revisions yet.