英文:
How to count items in a Go map?
问题
如果我想要计算地图结构中的项目数量,我应该使用什么语句?
我尝试使用
for _, _ := range m {...}
但是似乎语法是错误的。
英文:
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.
答案1
得分: 232
使用len(m)
。来自http://golang.org/ref/spec#Length_and_capacity
len(s) string类型 字符串长度(以字节为单位)
[n]T, *[n]T 数组长度(== n)
[]T 切片长度
map[K]T map长度(定义的键的数量)
chan T 通道缓冲区中排队的元素数量
以下是从现已停用的SO文档移植的几个示例:
m := map[string]int{}
len(m) // 0
m["foo"] = 1
len(m) // 1
如果变量指向nil
map,则len
返回0。
var m map[string]int
len(m) // 0
摘自Maps - Counting map elements。原作者是Simone Carletti。归属详细信息可在贡献者页面上找到。该来源受CC BY-SA 3.0许可,可在文档存档中找到。参考主题ID:732,示例ID:2528。
英文:
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.
答案2
得分: 5
对于想要计算嵌套映射中元素数量的任何人:
var count int
m := map[string][]int{}
for _, t := range m {
count += len(t)
}
英文:
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)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论