如何在Go语言中计算一个map中的元素数量?

huangapple go评论144阅读模式
英文:

How to count items in a Go map?

问题

如果我想要计算地图结构中的项目数量,我应该使用什么语句?
我尝试使用

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

但是似乎语法是错误的。

英文:

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

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

but it seems the syntax is false.

答案1

得分: 232

使用len(m)。来自http://golang.org/ref/spec#Length_and_capacity

  1. len(s) string类型 字符串长度(以字节为单位)
  2. [n]T, *[n]T 数组长度(== n
  3. []T 切片长度
  4. map[K]T map长度(定义的键的数量)
  5. chan T 通道缓冲区中排队的元素数量

以下是从现已停用的SO文档移植的几个示例:

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

如果变量指向nil map,则len返回0。

  1. var m map[string]int
  2. 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

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

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

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

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

  1. var m map[string]int
  2. 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

对于想要计算嵌套映射中元素数量的任何人:

  1. var count int
  2. m := map[string][]int{}
  3. for _, t := range m {
  4. count += len(t)
  5. }
英文:

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

  1. var count int
  2. m := map[string][]int{}
  3. for _, t := range m {
  4. count += len(t)
  5. }

huangapple
  • 本文由 发表于 2012年9月22日 22:31:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/12544641.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定